text:
Q: Custom Insert and Update methods defeated by automatic Save I am porting a Grails application from Oracle to MySQL database. The original Oracle version is a legacy database which uses a few complex Views leveraging Oracle's INSTEAD OF INSERT OR UPDATE feature which MySQL doesn't have. As a workaround I have implement Insert and Update methods on the Domain classes which point to these kinds of Views.  For example,
class AdminUser {
    //...
    def update() {
        if(this.validate()) {
            Sql sql = Utils.getHibernateSql()

            sql.execute(
                "update table_x ...",
                [...]
            )

            sql.execute(
                "update table_y ...)",
                [...]
            )

            sql.execute(
                "update table_z ...",
                [...]
            )

            return true
        }

        return false
    }
    //...
}

Here is a description of the problem I am running into at the moment:

*

*Within a service method I load an instance of AdminUser using AdminUser.get

*I modify the loaded instance and call update(), all appears well

*Once the service method finishes executing an exception is thrown due to something calling save on the instance.

How can I prevent the magical save happening in step (3) (I recently read somewhere that Grails will automatically save a modified Domain class instance which hasn't yet been saved upon exiting a service method, but I can't seem to find the link to that resource right now)?

A: You're leaving the modified instance in the hibernate session with dirty fields.  When the hibernate session gets flushed, it will try to save the object again with the usual save() method.
One solution would be to discard your object from the hibernate session after you've manually saved the changes.  For example:
def update() {
    if(this.validate()) {
        Sql sql = Utils.getHibernateSql()

        sql.execute(
            "update table_z ...",
            [...]
        )

        ...

        this.discard()  // remove the object from the hibernate session
        return true
    }

In addition, you can add this to your Config.groovy to require that objects be saved explicitly:
hibernate.flush.mode="manual"

A: If you use read() instead of get(), then the object will not auto-persist changes. You can still call save() explicitly, but the standard behavior where the OpenSessionInView interceptor flushes all unsaved dirty instances will skip the instances loaded with read().


text:
Q: Assigning array references, incompatible types? I have a custom class called ItemComponent.  Another class has an array of them called subComponents.  It's a property of the class:
ItemComponent *subComponents[0];

Initially, it is set as 0, because not all objects will have sub-components.
In the implementation, I have a method to add an ItemComponent to the property.  The item is passed in, and the assignment is coded like this (after necessary checks & switching):
ItemComponent *tempArray[1];
tempArray[0] = item;
subComponents = tempArray;

I get the error:  'incompatible types in assignment' on the last line.
They are both pointers to arrays, so what gives?
Thanks!

A: First, as I already wrote in a comment, I think you are sweating it too much. I guess we are talking about some game object that can have some components in it. In this case it is perfectly affordable to keep the components in an NSArray. The code will be easier to work with and the speed difference will be small.
If you want to sleep without worries, set up a small test that will iterate over some NSMutableArrays several thousand times and maybe even change some of them. Then measure the time it takes:
double start = CFAbsoluteTimeGetCurrent();
// now iterate over the arrays, send some messages, change contents
double end = CFAbsoluteTimeGetCurrent();
double diff = end-start; // in seconds
NSAssert(diff < 0.005, @"I'll be damned.");

(The 0.005 part might be too steep depending on what you are trying to do, but I guess you get the point. 50 fps ≈ 1/50 s = 0.02 s = 20 ms for a whole frame to build. If the whole Objective-C overhead took 10 ms, you'd still have about 20 ms for the rest and keep a decent framerate of 30 fps.)
There are cases where you would want to use plain C array, for example when you're writing a particle engine and have several thousands of items in an array that changes every loop. In that case you can simply use a pointer:
ItemComponent *components;
int compMax;
// …
compMax = 1000;
components = calloc(compMax, sizeof(ItemComponent));
NSAssert(components != NULL, @"Out of memory for components.");
components[0] = …;
components[1] = …;
// …
free(components);

I am hundred percent sure about the first point. I am not that much sure about the second, maybe there's a safer way to do it, but I would write it this way.

A: Is there a reason you're using C arrays instead of NSMutableArrays?

A: Try this to see if it makes a difference.
ItemComponent *subComponents[];

The way you have it defined, the subComponents array actually stores its (zero) item right there among your other class variables.  You can't reset it to point elsewhere.  In order to do that, you need to make it a pointer to a pointer to ItemComponent, instead of an array of zero length of ItemComponents.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift and mutating struct There is something that I don't entirely understand when it comes to mutating value types in Swift.
As the "The Swift Programming Language" iBook states:  By default, the properties of a value type cannot be modified from within its instance methods.
And so to make this possible we can declare methods with the mutating keyword inside structs and enums.
The thing that is not entirely clear to me is this:
You can change a var from outside a struct, but you cannot change it from its own methods. This seems counter-intuitive to me, as in Object Oriented languages, you generally try to encapsulate variables so they can only be changed from within. With structs this appears to be the other way around. To elaborate, here's a code snippet:
struct Point {
    var x = 0, y = 0
    mutating func moveToX(x: Int, andY y:Int) { //Needs to be a mutating method in order to work
        self.x = x
        self.y = y
    }
}

var p = Point(x: 1, y: 2)
p.x = 3 //Works from outside the struct!
p.moveToX(5, andY: 5)

Does anyone know the reason why structs cannot change their content from inside their own context, while the contents can easily be changed elsewhere?

A: The mutability attribute is marked on a storage (constant or variable), not a type. You can think struct has two modes: mutable and immutable. If you assign a struct value to an immutable storage (we call it let or constant in Swift)  the value becomes immutable mode, and you cannot change any state in the value. (including calling any mutating method)
If the value is assigned to a mutable storage (we call it var or variable in Swift), you're free to modify the state of them, and calling of mutating method is allowed.
In addition, classes don't have this immutable/mutable mode. IMO, this is because classes are usually used to represent reference-able entity. And reference-able entity is usually mutable because it's very hard to make and manage reference graphs of entities in immutable manner with proper performance. They may add this feature later, but not now at least.
For Objective-C programmers, mutable/immutable concepts are very familiar. In Objective-C we had two separated classes for each concept, but in Swift, you can do this with one struct. Half work.
For C/C++ programmers, this is also very familiar concept. This is exactly what const keyword do in C/C++.
Also, immutable value can be very nicely optimised. In theory, Swift compiler (or LLVM) can perform copy-elision on values passed by let, just like in C++. If you use immutable struct wisely, it will outperform refcounted classes.
Update
As @Joseph claimed this doesn't provide why, I am adding a little more.
Structs have two kind of methods. plain and mutating methods. Plain method implies immutable (or non-mutating). This separation exists only to support immutable semantics. An object in immutable mode shouldn't change its state at all.
Then, immutable methods must guarantee this semantic immutability. Which means it shouldn't change any internal value. So compiler disallows any state changes of itself in a immutable method. In contrast, mutating methods are free to modify states.
And then, you may have a question of why immutable is the default? That's because it's very hard to predict the future state of mutating values, and that usually becomes the main source of headaches and bugs. Many people agreed that the solution is avoiding mutable stuffs, and then immutable by default was on top of wish list for decades in C/C++ family languages and its derivations.
See purely functional style for more details. Anyway, we still need mutable stuffs because immutable stuffs have some weaknesses, and discussing about them seems to be out of topic.

A: Swift structs can be instantiated as either constants (via let) or variables (via var)
Consider Swift's Array struct (yes it's a struct).
var petNames: [String] = ["Ruff", "Garfield", "Nemo"]
petNames.append("Harvey") // ["Ruff", "Garfield", "Nemo", "Harvey"]

let planetNames: [String] = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planetNames.append("Pluto") //Error, sorry Pluto. No can do

Why didn't the append work with the planet names? Because append is marked with the mutating keyword. And since planetNames was declared using let, all methods thus marked are off limits.
In your example the compiler can tell you're modifying the struct by assigning to one or more of its properties outside of an init. If you change your code a bit you'll see that x and y aren't always accessible outside the struct. Notice the let on the first line.
let p = Point(x: 1, y: 2)
p.x = 3 //error
p.moveToX(5, andY: 5) //error

A: Consider an analogy with C++. A struct method in Swift being mutating/not-mutating is analogous to a method in C++ being non-const/const. A method marked const in C++ similarly cannot mutate the struct.

You can change a var from outside a struct, but you cannot change it
  from its own methods.

In C++, you can also "change a var from outside the struct" -- but only if you have a non-const struct variable. If you have a const struct variable, you cannot assign to a var, and you also cannot call a non-const method. Similarly, in Swift, you can change a property of a struct only if the struct variable is not a constant. If you have a struct constant, you cannot assign to a property, and you also cannot call a mutating method.

A: Caution: layman's terms ahead.
This explanation isn't rigorously correct at the most nitty-gritty code level. However it has been reviewed by a guy who actually works on Swift and he said it's good enough as a basic explanation.
So I want to try to simply and directly answer the question of "why".
To be precise: why do we have to mark struct functions as mutating when we can change struct parameters without any modifying keywords?
So, big picture, it has a lot to do with the philosophy that keeps Swift swift.
You could kind of think of it like the problem of managing actual physical addresses. When you change your address, if there are a lot of people who have your current one, you have to notify all of them that you've moved. But if no one has your current address, you can just move wherever you want, and no one needs to know.
In this situation, Swift is kind of like the post office. If lots of people with lots of contacts move around a lot, it has a really high overhead. It has to pay a big staff of people to handle all those notifications, and the process takes up a lot of time and effort. That's why Swift's ideal state is for everyone in its town to have as few contacts as possible. Then it doesn't need a big staff for handling address changes, and it can do everything else faster and better.
This is also why Swift-folks are all raving on about value types vs. reference types. By nature, reference types rack up "contacts" all over the place, and value types usually don't need more than a couple. Value types are "Swift"-er.
So back to small picture: structs. Structs are a big deal in Swift because they can do most of the things objects can do, but they're value types.
Let's continue the physical address analogy by imagining a misterStruct that lives in someObjectVille. The analogy gets a little wonked up here, but I think it still is helpful.
So to model changing a variable on a struct, let's say misterStruct has green hair, and gets an order to switch to blue hair. The analogy gets wonked, like I said, but sort of what happens is that instead of changing misterStruct's hair, the old person moves out and a new person with blue hair moves in, and that new person begins calling themselves misterStruct. No one needs to get a change of address notification, but if anyone looks at that address, they'll see a guy with blue hair.
Now let's model what happens when you call a function on a struct. In this case, it's like misterStruct gets an order such as changeYourHairBlue(). So the post office delivers the instruction to misterStruct "go change your hair to blue and tell me when you're done."
If he's following the same routine as before, if he's doing what he did when the variable was changed directly, what misterStruct will do is move out of his own house and call in a new person with blue hair. But that's the problem.
The order was "go change your hair to blue and tell me when you're done," but it's the green guy who got that order. After the blue guy moves in, a "job complete" notification still has to be sent back. But the blue guy knows nothing about it.
[To really wonk up this analogy something awful, what technically happened to green-haired guy was that after he moved out, he immediately committed suicide. So he can't notify anyone that the task is complete either!]
To avoid this problem, in cases like this only, Swift has to go in directly to the house at that address and actually change the current inhabitant's hair. That is a completely different process than just sending in a new guy.
And that's why Swift wants us to use the mutating keyword!
The end result looks the same to anything that has to refer to the struct: the inhabitant of the house now has blue hair. But the processes for achieving it are actually completely different. It looks like it's doing the same thing, but it's doing a very different thing. It's doing a thing that Swift structs in general never do.
So to give the poor compiler a little help, and not make it have to figure out whether a function mutates the struct or not, on its own, for every single struct function ever, we are asked to have pity and use the mutating keyword.
In essence, to help Swift stay swift, we all must do our part. :)

A: A structure is an aggregation of fields; if a particular structure instance is mutable, its fields will be mutable; if an instance is immutable, its fields will be immutable.  A structure type must thus be prepared for the possibility that the fields of any particular instance may be mutable or immutable.
In order for a structure method to mutate the fields of the underlying struct, those fields have to be mutable.  If a method that mutates fields of the underlying struct is invoked upon an immutable structure, it would try to mutate immutable fields.  Since nothing good could come of that, such invocation needs to be forbidden.
To achieve that, Swift divides structure methods into two categories: those that modify the underlying structure, and thus may only be invoked on mutable structure instances, and those that do not modify the underlying structure and should thus be invokable on both mutable and immutable instances.  The latter usage is probably the more frequent, and is thus the default.
By comparison, .NET presently (still!) offers no means of distinguishing structure methods that modify the structure from those that don't.  Instead, invoking a structure method on an immutable structure instance will cause the compiler to make a mutable copy of the structure instance, let the method do whatever it wants with it, and discard the copy when the method is done.  This has the effect of forcing the compiler to waste time copying the structure whether or not the method modifies it, even though adding the copy operation will almost never turn what would be semantically-incorrect code into semantically-correct code; it will merely cause code that is semantically wrong in one way (modifying an "immutable" value) to be wrong in a different way (allowing code to think it's modifying a structure, but discarding the attempted changes).  Allowing struct methods to indicate whether they will modify the underlying structure can eliminate the need for a useless copy operation, and also ensures that attempted erroneous usage will get flagged.

A: I wondered the same thing when I started learning Swift, and each of these answers, while adding some insights perhaps, are kind of wordy and confusing in their own right. I think the answer to your question is actually pretty simple…
The mutating method defined inside your struct wants permission to modify each and every instance of itself that will ever be created in the future. What if one of those instances gets assigned to an immutable constant with let? Uh oh. To protect you from yourself (and to let the editor and compiler know what you're trying to do), you're forced to be explicit when you want to give an instance method this sort of power.
By contrast, the setting of a property from outside your struct is operating on a known instance of that struct. If it's assigned to a constant, Xcode will let you know about it the moment you've typed in the method call.
This is one of the things I'm loving about Swift as I start to use it more—being alerted to errors as I type them. Sure beats the heck out of troubleshooting obscure JavaScript bugs!

A: SWIFT : Use of mutating function in Structs
Swift programmers developed Structs in such a way that properties of it can not be modified within Struct methods. For example, Check the code given below
struct City
{
  var population : Int
  func changePopulation(newpopulation : Int)
  {
      population = newpopulation //error: cannot modify property "popultion"
  }
}
  var mycity = City(population : 1000)
  mycity.changePopulation(newpopulation : 2000)

On executing the above code we get an error because we are trying to assign a new value to the property population of the Struct City. By default Structs properties can't be mutated inside its own methods. This is how Apple Developers have built it, so that the Structs will have a static nature by default.
How do we solve it? What's the alternative?
Mutating Keyword :
Declaring function as mutating inside Struct allows us to alter properties in Structs.
Line No : 5, of the above code changes to like this,
mutating changePopulation(newpopulation : Int)

Now we can assign the value of the newpopulation to property population to within the scope of the method.
Note :
let mycity = City(1000)
mycity.changePopulation(newpopulation : 2000)   //error: cannot modify property "popultion"

If we use let instead of var for Struct objects, then we can't mutate the value of any properties, Also this is the reason why we get an error when we try to invoke mutating function using let instance. So it is better to use var whenever you are changing value of a property.
Would love to hear your comments and thoughts…..

A: Swift mutating struct
One more variant
struct MyStruct {
    var myVar = "myVar"
    let myLet = "myLet"
}

func testMutateString() {
    //given
    let myStruct = MyStruct()

    //Change var
    //when
    var myStructCopy = myStruct
    myStructCopy.myVar = "myVar changed 1"

    //then
    XCTAssert(myStructCopy.myVar == "myVar changed 1")

    //Change let
    //when
    withUnsafeMutableBytes(of: &myStructCopy) { bytes in
        let offset = MemoryLayout.offset(of: \MyStruct.myLet)!
        let rawPointerToValue = bytes.baseAddress! + offset
        let pointerToValue = rawPointerToValue.assumingMemoryBound(to: String.self)
        pointerToValue.pointee = "myLet changed"
    }

    //then
    XCTAssert(myStructCopy.myLet == "myLet changed")
}

[Swift types]


text:
Q: What is an effective means to make divisibility tests a mathematical 'habit', particularly for algebra? Divisibility tests are a useful problem-solving technique for particularly dealing with larger numbers (thousands etc) and algebraic problems. However, I have always found that many students will just reach for the calculator, many not even realising the simpler tests, such as anything divisible by 2, 5 or 10.
What is an effective means to help 'train' these skills in students as a problem solving and 'thinking' skill?

A: The students are the smart ones. If the calculator is giving the easiest way to get the answer of course the best is to use the calculator.
But what would happen if the problem is so designed that a calculator would be of little or no help.
Calculators don\t help much to show that $n(n+1)$ is even. That $a+10b+100c+1000d$ is divisible by $9$ if and only if $a+b+c+d$ is divisible by $9$. That $3^{3^{3^{3^{3^{3}}}}}-1$ is even.
... and these are still not clever exercises.
Addendum:
Because it is relevant, I would like to advocate against training students to mindlessly using some tricks, techniques, procedures. Students in their brute state are critical enough by nature. Pushing them to do some task for which there is not a clear purpose is what turns them into bad students. In mathematics we often focus too much in teaching the techniques, but what is more important is the purpose for those techniques. That is why you often see students that compulsively 'simplify' solutions, even partial solutions, or expand brackets for no reason.
This applies to any technique. Give them exercises in which it is clear the purpose of a technique. Being able to identify a purpose, not knowing lots of procedures, is what makes them able to solve new problems. Procedures and techniques can be googled most of the time.

A: You could race them; if you can always beat them in your head when they use a calculator, that would convince them. Then have them race each other, one with a calculator, one without, then switch until they get good at it.


text:
Q: Web Speech API - SpeechSynthesisUtterance onmark event wont fire I cannot get the "onmark" event to fire in Chrome or Edge while using SSML.
I have tried this in Chrome and Edge and wrote code based on standards at https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

            <input id="btnSpeak" type="button" onclick="Speak(); return false;" value="Speak" />

    </form>

A: The onboundary event doesn't seem to be fired correctly on Chrome, for voices based on remote tts services. Check the localService property for voices you intend to use, select localService = true voices only.
On Edge the onboundary event is aways fired correctly for all voices.
Oddly, Chromium team has marked this known issue as "wontfix",
https://bugs.chromium.org/p/chromium/issues/detail?id=521666


text:
Q: FtpWebRequest can't handle filenames that start with dash or dot I am creating an ftp based utility with c# .net 4 with a backend filezilla server. It works fine until my depth search meets a folder starting with (-) dash or (.) dot. I researched the net a bit, found out you cannot have filenames starting with dash or dot in ftp for reasons I understood. I tried encoding the uri as suggested changing "." with "%2E" and "-" with "%2D" and - with ./- without any improvement (in step by step debugging I saw it change succesfully but filezilla server logged a 550 error), HttpUtilities.UriEncoding gave me the same result. Very strange behaviour though as it seems ftp LISTS the parent directory of the asked one. So for example when I try to LIST the directory /games/-randomdir I get the list of /games again resulting to a new false uri of the depth search /games/-randomdir/-randomdir! See for yourself the server's interface answer:
(127.0.0.1)> CWD /
(127.0.0.1)> 250 CWD successful. "/" is current directory.
(127.0.0.1)> CWD a00000001/game
(127.0.0.1)> 250 CWD successful. "/a00000001/game" is current directory.
(127.0.0.1)> PASV
(127.0.0.1)> 227 Entering Passive Mode (127,0,0,1,194,205)
(127.0.0.1)> LIST -eclipse
(127.0.0.1)> 150 Opening data channel for directory listing of "/a00000001/game"
(127.0.0.1)> 226 Successfully transferred "/a00000001/game"

It succesfully transfers the content of game, not -eclipse which LIST asks.
That is because LIST -eclipse is perfectly valid (although not existing) command for the emulated server. So it LISTS again "games" with the extra command "eclipse". But, how can I escape it?

A: Found this! It's hacky but works. On your URI you need to add a last slash "/" so the FTP will change folder before listing like this!
Uri u = new Uri("ftp://" + ip.ToString() + (folder) + "/", UriKind.Absolute);


text:
Q: Logstash float field does not been indexed The following is the configuration of logstash. When I input log into logstash, it works well as expected. All the field can be accepted by elasticsearch and the value and type of all fields is correct. However, when I view the log in kinana, it says that the cost field is not indexed so that it can't been visualized. While all the string fields are indexed. I want to visualize my float field. Anyone know what's the problem?
input {
    syslog {
        facility_labels=>["local0"]
    port=>515
    }
    stdin {}
}

filter{
    grok {
        overwrite => ["host", "message"]
        match => { "message" => " %{BASE10NUM:cost} %{GREEDYDATA:message}" }
}
mutate {
        convert => { "cost" => "float" }
    }
}
output {
    stdout{
        codec=>rubydebug
    }
    elasticsearch{  }
}

A: Kibana doesn't autoreload a new field from Elastic Search. You need to reload it manually.
So you go in the Settings tab, select you index and reload the fields


text:
Q: Java - How to split array on each iteration and pass into a function efficiently? I have an array that holds some values and a function that takes in two arrays. What I want to do is split the array so that the last element is not in the array so I have two arrays, one that has all the original elements except the last and one that has just one element - the last. After I pass this into a function, I want to use the original array but this time put the second last element into a seperate array and so on. I want to do this five times. The following will explain it better:
int[] val = {25,50,66,75,100,1000,5000,10000,25000};

for (int i=0; i<5; i++){

//Need to split the array and then pass it to the function here
}

public void evaluate(int[] train, int[] test){

....
}

So for example in the first iteration I want to remove/split 25000 from the array and put it into another array and then pass the two arrays throught the function:
first array now has {25,50,66,75,100,1000,5000,10000}
and second array now has {25000}
On next iteration I want to now split/remove 10000 (25000 is now back in the array):
so first array now has {25,50,66,75,100,1000,5000,25000}
and second array now has {10000}
So basically it is going from the bottom and working its way up, but only 5 times.

A: The easiest thing to do would be to switch from using arrays to using a List<Integer>. You can then use the subList method to construct arrays that are subsequences of the original array.
If you insist on using arrays, you have two options:

*

*Add arguments to represent the start and end index of the applicable range for each array argument. You then need to rewrite your logic to go from start through end-1 (instead of 0 through array.length - 1).

*Allocate new arrays and copy the data into them. This won't work if you intend to modify the array elements and in any case is a lot of extra work.

Here's some code to show how to use a List<Integer>:
// autobox each value as an Integer:
List<Integer> vals = Arrays.asList(
    new Integer[] {25,50,66,75,100,1000,5000,10000,25000});
final int len = vals.length();

for (int i=0; i<5; i++){
    evaluate(vals.subList(0, i), vals.subList(i, len));
}

public void evaluate(List<Integer> train, List<Integer> test){

....
}

A: check out the Arrays API you can do it with the Arrays.copyOf(..) method.
newArray = Arrays.copyOf(oldArray, oldArray.length-1)

Perhaps this code can help you you.
    int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    int[] firstArray = new int[val.length-1];
    int[] SecondArray = new int[1];
    //iterates the whole array set to 5 if needed
    for (int n = 0; n < val.length; n++) {
        SecondArray[0] = val[val.length-n-1];
        for(int x = 0, firstArrayCounter= 0; x < val.length; x++){
            if(val[x]!=SecondArray[0]){
                firstArray[firstArrayCounter] = val[x];
                firstArrayCounter++;
            }
        }
        //prints what is in the arrays
        for (int i = 0; i < firstArray.length; i++)
            System.out.print(firstArray[i] + " ");
        System.out.println("\n"+SecondArray[0]);
    }

Good luck!

A: I dunno what you are trying to do in the end but this seems to be a perfect fit for a functional programing language. Anyway we can do it in java and moreover with arrays :
In you for loop that's going from 1 to 5 included you might put something like :
for (int i=1; i<=5; i++){
  int[] train = new int[val.length-i];
  System.arraycopy( val, 0, train, 0, train.length-1 );
  int test = new int[1];
  test[0] = val[val.length-i];
  evaluate(train,test);
}

A: The algorithm I would use is:

*

*Take the original array, A, and create a new A' with 1 less element and a single-element array, call it B.

*Populate A' with n-1 elements, populate B with 1 element.

*Then, when you've completed processing A' and B, swap the appropriate element in A' with B[0].

The single copy is O(n) and each of the 5 iterations has a constant time operation to do the swap. Memory is also O(n).

A: You can use ArrayUtils of Apache commons, code example is like as follows:
    private static int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    private static int[] test = {};

    public static void evaluate(int[] train, int[] test) {
        for (int i = 0; i < train.length; i++) {
            System.out.print(train[i] + ",");
        }
        System.out.println("");
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i] + ",");

        }
        System.out.println("");
        System.out.println("-----");
    }

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            if (!ArrayUtils.isEmpty(test))
                ArrayUtils.remove(test, 0);
            evaluate(ArrayUtils.remove(val, val.length - 1 - i), ArrayUtils.add(test, val[val.length - 1 - i]));
        }
    }

A: Create the two arrays up front, and swap one element into your test array after each iteration. This will be faster than allocating new arrays all the time.
int[] val = {25,50,66,75,100,1000,5000,10000,25000};

// create the destination arrays:
int[] train = new int[val.length-1];
int[] test = new int[1];

// initialize the arrays:
test[0] = val[val.length-1];
for (int i = 0; i < val.length-1; ++i)
{
    train[i] = val[i];
}

int timesToIterate = 5;

for (int iteration = 0; iteration < timesToIterate; ++iteration)
{
    evaluate(train, test);

    int i = train.length-1-iteration;
    if (i >= 0) // don't swap if this is the last element in the array
    {
        int tmp = test[0];
        test[0] = train[i];
        train[i] = tmp;
    }
}

With your example data, the arrays passed into the evaluate function are:
{25 50 66 75 100 1000 5000 10000 } {25000}
{25 50 66 75 100 1000 5000 25000 } {10000}
{25 50 66 75 100 1000 10000 25000 } {5000}
{25 50 66 75 100 5000 10000 25000 } {1000}
{25 50 66 75 1000 5000 10000 25000 } {100}


text:
Q: Git Rebase seems to have worked but all commits are still showing in the log... what state am I in? I think I squashed the last 40 commits using rebase.
I was following this guide to make sure I didn't do anything stupid - http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
The problem is, I think I did something stupid.
The (interactive) text file couldn't be saved, so it seems that the rebase failed but the message it gave and some other things below suggest it might have worked.
Not sure where I am or what to do (or even what my name is).
Here's what I did:

*

*I typed git rebase -i HEAD~40

*A text file came up, which I edited, by changing all lines to start with 'squash' except the top one

*I'm on windows, using EditPad... the file can't be saved! Oh noes... (read-only/permissions?).

*I save it to a random directory.

*The command line shows some sort of success (unfortunately I've lost the message). I don't know how it could succeed or know where the file I saved is...

*git rebase --continue says "No rebase in progress?

*git reflog suggests it worked (from what I know at least, the word 'rebase' is showing on the last 40 odd commits) eg:
9992445 HEAD@{8}: rebase: reports working

*but running git log shows all 40 commits I just 'rebased'

This isn't looking good. Does anyone know what state I'm in?
Am I in limbo, was this a zombie rebase?

A: This question is about a slightly surprising aspect of the behaviour of git rebase -i.  If you close the editor window without making any changes, then the rebase still takes place.1  (This is very different from the action when the editor for commit messages is popped up, where exiting your editor without making any changes aborts the commit.)
In your case, since you saved the interactive rebase list elsewhere, and then exited the editor, git assumed that you just want to reapply all those commits as before - it has no way of telling that you saved the file elsewhere.  If the history was linear between HEAD and HEAD~40 then the history will be exactly the same (including the object names of each commit), but if it was non-linear you will have rewritten your history so that it's linear (and so will have different object names for some of the commits).
You might want to check in the reflog that HEAD has the same object name (hash) before and after the rebase to check this.
1 Although in the version I'm using, if git can tell that the result would be exactly the same it doesn't bother to actually reapply the commits and just puts a single entry in the reflog.  However, that optimization clearly hasn't taken place in your situation, since you can see the reapplication of each commit in the reflog.

A: If the rebase "todo list" couldn't be saved, your rebase didn't work.
The easiest way to squash that many commits would be to do git reset --soft HEAD~40 and then git commit with your new message - assuming you want to squash all of them.


text:
Q: GIS through Games: Ideas or Links I'm managing a project - http://nepanode.anl.gov aimed at improving data awareness and sharing around Environmental impact analysis. I'm struggling to come up with ways to engage users and show them how they can apply the site. I'm looking for specific ideas, games, demos, tutorials to demonstrate how the site can be used; looking for new ideas and/or links to existing training resources that aim to engage users through games or case studies? Limited to users only using the site and/or using QGIS

A: Here is one example from the John Hutton Institute in Aberdeen (formerly The Macaulay Institute - where I headed up their commercial GIS team, though didn't create this game), Scotland, which might provide some ideas.


text:
Q: Cannot install openjdk-8-jre successfully On 18.04 pcu29@pcu29:~$ sudo apt-get install openjdk-8-jre
[sudo] password for pcu29:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  openjdk-8-jre-headless
Suggested packages:
  icedtea-8-plugin fonts-ipafont-gothic fonts-ipafont-mincho
  fonts-wqy-microhei fonts-wqy-zenhei
The following NEW packages will be installed:
  openjdk-8-jre openjdk-8-jre-headless
0 upgraded, 2 newly installed, 0 to remove and 173 not upgraded.
Need to get 0 B/27.5 MB of archives.
After this operation, 100 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Selecting previously unselected package openjdk-8-jre-headless:amd64.
dpkg: unrecoverable fatal error, aborting:
 files list file for package 'astyle' is missing final newline
E: Sub-process /usr/bin/dpkg returned an error code (2)

A: The file is corrupted. Remove it using:
sudo rm /var/lib/dpkg/info/astyle.list

Then reinstall the package using:
sudo apt install --reinstall openjdk-8-jre


text:
Q: Why do I have to call an XML element in function and not in onCreate? Full code of onCreate is here:
//Global variables
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
int expandedGroup = -1;
boolean notification;
boolean vibrate;
String ringtone;
int hour;
int minutes;
int day;

//UI elementi
TextView dan;
TextView ura;
ImageView facebook;
ImageView twitter;
TextView tw1, tw2, tw3, tw4, tw5, tw6, tw7, tw8, tw9, tw10, tw11, tw12, tw13, tw14, tw15, tw16, tw17, tw18, tw19, tw20, tw21, tw22, tw23, tw24, tw25, tw26, tw27, tw28, tw29, tw30;
Button nadomescanja;

//Mapa aplikacije
public static File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.whizzapps.stpsurniki/");

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

    //Mapa aplikacije se naredi, če ne obstaja
    if (!appDir.exists())
    {
        appDir.mkdirs();
    }

    //Povezava z elementi iz navigacije
    expListView = (ExpandableListView) findViewById(R.id.lvExp);
    dan = (TextView) findViewById(R.id.dan);
    ura = (TextView) findViewById(R.id.ura);
    tw15 = (TextView) findViewById(R.id.textView22);
    facebook = (ImageView) findViewById(R.id.facebook);
    twitter = (ImageView) findViewById(R.id.twitter);

    //Nastavitev glave in noge
    View headerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
    View footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
    expListView.addHeaderView(headerView);
    expListView.addFooterView(footerView);

    //Nastavitev ExpandableListView adapterja
    prepareListData();
    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
    expListView.setAdapter(listAdapter);

    //Klicanje pomembnih funkcij
    nadomescanjaClickListener();
    setCustomFontToAllTextViews();
    loadRandomQuote();
    getDay();
    getTime();
    expListViewClickListeners();
    posodabljanjeUre();
}

So as you can see, before the onCreate method i declare the global variables and then in onCreate instantiate those variables. Then a few lines after that I call all the methods that I need to execute in onCreate. But those methods then crash the app because of nullpointerexception (they don't get the variable yet). But if I delete those variables in onCreate and instantiate them in the method itself then it works.
I can't post the logcat at the moment because I'm not at home but I can let you know that it's a simple nullpointerexception error becuase it doesn't get those variables that I have set in onCreate.

A: facebook and twitter ImageView are not part of your Activity layout until they are added. so findViewById() will return null before your Views are added. search for the twitter and facebook Views after adding footerView to the expandableListView.
expListView.addFooterView(footerView);
facebook = (ImageView)footerView.findViewById(R.id.facebook);
twitter = (ImageView)footerView.findViewById(R.id.twitter);


text:
Q: Remove label in view Swift5 I'm adding a label programatically in my view, in viewDidAppear:
var label : UILabel!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
  ...........

      label = UILabel(frame: CGRect(x: 0,y: 0, width: 200, height: 40))
        label.numberOfLines=2
        label.textAlignment = .center
        label.attributedText = amountText
        label.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(label)
        constrains1 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0);
        constrains2 =  NSLayoutConstraint(item: label, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0);
        view.addConstraints([constrains1,constrains2])
  ............

This label has to be removed after purchase, but not work:
func buy(alert: UIAlertAction!) {

    self.view.setNeedsLayout()
    self.showSpinner(onView: self.view)

    SwiftyStoreKit.purchaseProduct("com...........", quantity: 1, atomically: true) { result in

        switch result {
        case .success(let purchase):
            DispatchQueue.global(qos: .background).async {

                DispatchQueue.main.async {
                    print("buy: \(purchase.productId)")

                    self.label.translatesAutoresizingMaskIntoConstraints = false
                    self.label.isHidden = true;

                    self.view.addConstraint(NSLayoutConstraint(item: self.label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0))

                    self.view.needsUpdateConstraints()
                    self.view.layoutIfNeeded()
                    self.removeSpinner()
                }

            }

I try removeFromSuperview, change color, change text...but nothing change label visibility.
What is the error??
Thanks a lot


text:
Q: UpdatePanel with input type other than text in html5 I am developing an open source project for rendering HTML5 using ASP.NET. Here you can take a look:
http://asphtml5.codeplex.com/
now I have a problem with update panel in posting back the input values that have type other than 'text'. as you might know, html 5 has introduced several input types, for example 'number', 'tel', 'search', etc. Now if I render such controls, everything works fine in normal situations, but if I put them inside an UpdatePanel, no value will be posted back and the value will be reset.
here is a small piece of code that produces the same error:
    <asp:UpdatePanel runat="server" ID="UP">
        <ContentTemplate>

                Enter A Number:
                <asp:TextBox runat="server" ID="Number2" type="number" />

            <asp:Button Text="Submit" runat="server" ID="BtnSubmit" OnClick="BtnSubmit_Click" />

                You entered :
                <asp:Label Text="" ID="LblValue" runat="server" />

        </ContentTemplate>
    </asp:UpdatePanel>

if you test this code on a browser that supports html 5, lets say Chrome as an example, a Numeric Up-Down field will be shown. but if you click on the submit button, it will lose the value that you have entered.
here is the code for event handler:
        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            LblValue.Text = Number2.Text;
        }

what I have already tried is reading UpdatePanel, ScriptManager and ScriptManagerProxy classes codes, nothing found.
I think I might need to create my own UpdatePanel and/or ScriptManager classes for use.
Could anyone help me, and tell me where to check.

A: Interestingly enough, the ASP.NET 4.0 AJAX framework does seem to be aware of HTML 5 input types (see code), yet as @TimSchmelter pointed out, this is confirmed by Microsoft as a bug.
This may give you a starting point for debugging the behavior and/or overriding the default behavior and finding a solution.
It could also be an error on the server-side processing code for these input types, although I'm not sure why they should/would care about an async postback versus a normal postback.
this._textTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;

function Sys$WebForms$PageRequestManager$_onFormSubmit(evt) {
        var i, l, continueSubmit = true,
            isCrossPost = this._isCrossPost;
        this._isCrossPost = false;
        if (this._onsubmit) {
            continueSubmit = this._onsubmit();
        }
        if (continueSubmit) {
            for (i = 0, l = this._onSubmitStatements.length; i < l; i++) {
                if (!this._onSubmitStatements[i]()) {
                    continueSubmit = false;
                    break;
                }
            }
        }
        if (!continueSubmit) {
            if (evt) {
                evt.preventDefault();
            }
            return;
        }
        var form = this._form;
        if (isCrossPost) {
            return;
        }
        if (this._activeDefaultButton && !this._activeDefaultButtonClicked) {
            this._onFormElementActive(this._activeDefaultButton, 0, 0);
        }
        if (!this._postBackSettings || !this._postBackSettings.async) {
            return;
        }
        var formBody = new Sys.StringBuilder(),
            count = form.elements.length,
            panelID = this._createPanelID(null, this._postBackSettings);
        formBody.append(panelID);
        for (i = 0; i < count; i++) {
            var element = form.elements[i];
            var name = element.name;
            if (typeof(name) === "undefined" || (name === null) || (name.length === 0) || (name === this._scriptManagerID)) {
                continue;
            }
            var tagName = element.tagName.toUpperCase();
            if (tagName === 'INPUT') {
                var type = element.type;
                if (this._textTypes.test(type)
                    || ((type === 'checkbox' || type === 'radio') && element.checked)) {
                    formBody.append(encodeURIComponent(name));
                    formBody.append('=');
                    formBody.append(encodeURIComponent(element.value));
                    formBody.append('&');
                }
            }
            else if (tagName === 'SELECT') {
                var optionCount = element.options.length;
                for (var j = 0; j < optionCount; j++) {
                    var option = element.options[j];
                    if (option.selected) {
                        formBody.append(encodeURIComponent(name));
                        formBody.append('=');
                        formBody.append(encodeURIComponent(option.value));
                        formBody.append('&');
                    }
                }
            }
            else if (tagName === 'TEXTAREA') {
                formBody.append(encodeURIComponent(name));
                formBody.append('=');
                formBody.append(encodeURIComponent(element.value));
                formBody.append('&');
            }
        }
        formBody.append("__ASYNCPOST=true&");
        if (this._additionalInput) {
            formBody.append(this._additionalInput);
            this._additionalInput = null;
        }

// truncated for length

A: All right then, I figured out a way to fix that.
First of all I found the problem with the code that Tim Medora provided. It all was the this. modifier's fault. So this JavaScript fixed the problem:
var _textTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function Sys$WebForms$PageRequestManager$_onFormSubmit(evt) {
...
if (_textTypes.test(type) ||
       (((type === 'checkbox') || (type === 'radio')) && element.checked)) {
       formBody.append(encodeURIComponent(name));
       formBody.append('=');
       formBody.append(encodeURIComponent(element.value));
       formBody.append('&');
...
}

Now I had to inject my function into ScriptResource.axd.
For now I found a way that seems to work:
I created a class ScriptResouceHandler that extends System.Web.Handlers.ScriptResourceHandler in namespace DotM.Html5.Handlers.
in its ProcessRequest I called base.ProcessRequest(context) to do its job. But I wanted to add my function to the one rendering original function. I found out that it was when the encrypted ZSystem.Web.Extensions,4.0.0.0,,31bf3856ad364e35|MicrosoftAjaxWebForms.debug.js| was passed.
Another problem was that in System.Web.Handlers.ScriptResourceHandler, 'Page.DecryptString' method which is internal is called to decrypt the query string param.
so there was no way for me to invoke that method via reflection.
here is the code:
        protected sealed override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            if (CypherContainsAjax(context.Request.QueryString["d"]))
                context.Response.Write(OnFormSubmit);
        }

        private bool CypherContainsAjax(string cypher)
        {
            var text = DecryptString(cypher);
            if (text == null)
                return true; //Then Add it everywhere. What else could I do? :D
            return text.Contains("MicrosoftAjaxWebForms");
        }

        private string DecryptString(string cypher)
        {
            if (PageDecryptString == null)
                return null;
            return (string)PageDecryptString.Invoke(null, new object[] { cypher });
        }
        private static MethodInfo PageDecryptString;
        static ScriptResourceHandler()
        {
            PageDecryptString = typeof(Page).GetMethod("DecryptString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
        }

You may call this some kind of ugly hacking ...

A: This was already fixed in .Net 4 Reliability Update 1 (there is also a version 2, but it does not contain the first one): http://support.microsoft.com/kb/2533523
But if you are using AjaxControlToolkit, it uses its own internal MicrosoftAjaxWebForms.js which is an older fork, and there is still no official fix for it - you can use mine solution from here: http://ajaxcontroltoolkit.codeplex.com/workitem/27041
So - you can either include the fixed ToolkitScriptManager with your project (a bloat, I know), or you can try to include the new version of MicrosoftAjaxWebForms.js by experimenting with vanilla ScriptManager properties AjaxFrameworkMode="Explicit", Scripts or CompositeScript.

Use the AjaxFrameworkMode property to enable all Microsoft Ajax script files, to disable all Microsoft Ajax script files, or to explicitly include individual script files.
The Scripts collection does not contain the core Microsoft Ajax Library scripts. The scripts in the core library are rendered automatically; they do not have to be registered with the ScriptManager control. However, if you want to override a core script or any control script and substitute a different version of the script, you can add your version to the Scripts collection.

<asp:ScriptManager runat="server">

</asp:ScriptManager>

You can get the new version of MicrosoftAjaxWebForms.js from System.Web.Extensions assembly Resources (with .Net Reflector) on machines with installed Reliability Update 1.


text:
Q: How to add ucwords and strtolower to this form I want "s.value" to be turned all to lowercase and then ucwords to it but I don't know how to do it since it's inside a form.
Basically I want to do something like this: ucwords(strtolower(   s.value here    ));
This is the form:
   <form role="search" method="get" id="searchform" action="http://chusmix.com/?s=" onsubmit="if (document.getElementById('s2').value.length > 5) window.location = action + '<php echo $city; ?>++++' + s.value; return false;" >

Thanks

A: Javascript String have two functions: toLowerCase() and toUpperCase, you can use them with
function toInitCap(input)
{
 input = input || "";
 return input.substring(0,1).toUpperCase() + input.substring(1,str.length).toLowerCase();
}

toInitCap(s.value)

A: <script type="text/javascript">

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

function strtolower (str) {
    return (str+'').toLowerCase();
}

</script>

<form role="search" method="get" id="searchform" action="http://chusmix.com/?s="  onsubmit="if (document.getElementById('s2').value.length > 5) window.location = action + '<?php echo $city; ?>++++' + ucwords(strtolower(s.value)); return false;" >

The javascript functions are from PHP.JS

A: You may, like me, want something that does this on one line, I used:
"your strING".toLowerCase().replace(/(?:(^.{1})|\ [a-z]{1})/g, function(a){return a.toUpperCase();})

returns Your String

A: + <?php echo ucwords(strtolower($s_value)); ?>;

A: You want to do:
$out = ucwords(strtolower($_GET['s.value']));

If s.value is the input name you want to pass

A: If you want to do it while they are editing the text within the text box then I'm not sure what you would do but if you want to make it lowercase then uppercase AFTER they submit the form then its simple.
ucwords(strtolower($_GET['formid']))

A: str.length => input.length
function toInitCap(input)
{
 input = input || "";
 return input.substring(0,1).toUpperCase() + input.substring(1,input.length).toLowerCase();
}

toInitCap(s.value)


text: Q: Allow partial external access to internal website. We have developed a new Purchase Order application that is used to send PO's to vendors via email. The email contains a link at the bottom for the user to click to acknowledge receipt of the PO which is a link back into the system that updates the status of the PO. Doing this however exposes the login page of the application which I want to hide. Any suggest on how to hide this? We're Running an apache webserver on windows 2012 R2.


text:
Q: Asp.net MVC Routing always to Root with parameters Now, the question. I have an eCommerce website and I have a controller called Store with an action Index.  When someone types www.mysite.com/sony, I want to route to controller Store and action Index with parameter brand=Sony. If someone type www.mysite.com/sony-tv, I want to route to controller Store and action Index but with the parameters brand=sony and department=tv.
I obtained that by creating a route for every situation storing in a database, and building the routes dynamically when the app starts. Its works fine in a few cases.
First, i need to index the routes. I need to map the route sony-tv before the sony, otherwise the /sony-tv maps to /sony equally.
When i enter at site's home (www.mysite.com) and click at Url.Action("Index","Store", new {brand=Sony}) it route me to www.mysite.com/sony. NICE!. Now, inside the SONY brand i'll click at Url.Action("Index","Store", new {brand=sony, department=tv}) and I can see all TV's from Sony.
Everything is running fine until here.  In the database,  I have 1 route to /sony where I say i have a parameter named brand with value Sony and a constrained named brand with value Sony. I have another route saying the same way to sony-tv. The pattern sony-tv has a parameter named brand with value sony and a parameter named deparment with value tv, and the sames constraints of parameters.
In my head, its means that the route for www.mysite.com/Sony is Store/Index/brand=sony  and the www.mysite.com/sony-tv is Store/Index/brand=sony&department=tv. With the constraints, i understand that if department is not TV or if the parameter department does not exists, it will send to www.mysite.com/sony
When i'm at www.mysite.com/sony-tv, if I pass my mouse over the other brands, the link build to Url.Action("Index","Store", new {brand=Apple}) is www.mysite.com/Apple-Tv
I have a route to Apple-TV equal to Sony. The URL exists but i'm not passing the TV parameter. I passed on this link (brands links) only the brand. I want to move the user to brand's root he's moved to brands + department.
I don't know, its looks like the department variable is passing through again and I don't know how to cancel that.
I'm completely wrong? What i'm doing is valid? I can do that? Where is my mistake?
At cshtml file:
@Html.ActionLink(febrand.Name.ToUpper(), "Index", new { controller = "Store", brand= febrand.FriendlyName, department = string.Empty })

at final html file (show source code from google chrome):
SONY

A: Fisrt, that seems like a lot of work for something that you could do with two custom routes.  Additionally, as your route table gets larger (eg. adding more brands and/or departments), each request to your site will take longer to fulfill due to having to scan a larger list of routes.
So, lets attempt to fix your route table.  Place these two routes above your default route in the global.asax:
routes.MapRoute(
    "Department",
     "{brand}-{department}",
     new { controller = "Store", action = "Index" };

routes.MapRoute(
     "Brand",
      "{brand}",
      new { controller = "Store", action = "Index" });

As for your issue, when you create your action link, the routing engine is holding onto the department route value from the view you are currently on.  To make it forget that parameter when generating a link, send a null across for the department variable when you do not need it.
@Html.ActionLink("Apple", "Index", new{controller="Store", brand="Apple", department = string.empty});

EDIT
I feel you may be in a weird edge case with your routing (and there are numerous examples of this problem all across SO, such as here and here).  The solution, other than the one I provided, is to switch to Html.RouteLink instead of Html.ActionLink.
RouteLink Signature that we are going to use
Html.RouteLink(string linkText, string routeName, object RouteValues)

Example Brand link for your code
@Html.RouteLink(febrand.Name.ToUpper(), "Brand", new { controller = "Store", action = "Index", brand= febrand.FriendlyName})


text:
Q: A book about young adults kidnapped and sent to a harsh planet to colonize it? The book starts with a group of young adults graduating, some with dreams and others with no plan. They go out to a party on someone else's money (maybe he offered it to them with a mysterious catch?) and the main character (female) buys a red dress with it. At some point in the evening she either falls asleep, blacks out, or is struck and rendered unconscious. When she wakes up, she's on a plateau in a dusty place. Somehow (audio message) she finds out she's a colonist on a deadly planet, and she's on her own for survival. Her red dress is replaced by rough clothing or animal skins, and I'm pretty sure she doesn't have any weapons or supplies... Maybe a day's worth? Later on, she nearly dies from some bad berries she tried to eat, and is almost killed by an alien beast. She meets up with other forced colonists later.
I keep thinking that the story has to do with a test... She'll be rewarded in the end if she can survive?

A: Invitation to the Game by Monica Hughes?

The book is a hard science fiction dystopian novel set in 2154, a time
  when machines and robots perform most jobs. Because of this, very few
  people are employed, with many people living on a social welfare
  system for support. The unemployed people have nothing to look forward
  to, except various illicit drugs. Some have formed gangs, some are
  shown to be agitating for political reform (in chapter 5 there is a
  reference to leaflets printed up), and many are involved in organized
  crime of some form or another. The government, possibly the only
  government in existence at this point, is shown to have complete
  control over its citizens by restricting the unemployed to designated
  areas (DAs), and having similar control over the working-class.


text:
Q: Why angular 2 need node.js I don't have experience in front-end but I want to create a simple app using Angular 2.
Why do I need to install Node.js as a prerequisite step? Why does Angular use Node.js?

A: There are a couple of things that Angular uses Node.js for:

*

*Installing and managing packages. From the Quickstart tutorial:

Angular application developers rely on the npm package manager to install the libraries and packages their apps require. The Angular team recommends the starter-set of packages specified in the dependencies and devDependencies sections.

*

*Compiling the TypeScript used into JavaScript that the browser understands - browsers can't process TypeScript natively and the SystemJS imports used in your code aren't supported in browsers yet:

We strongly recommend transpiling (AKA compiling) to JavaScript during a build phase before running the application for several reasons including:
We see compiler warnings and errors that are hidden from us in the browser.
Precompilation simplifies the module loading process and it's much easier to diagnose problems when this is a separate, external step.
Precompilation means a faster user experience because the browser doesn't waste time compiling.
We iterate development faster because we only recompile changed files. We notice the difference as soon as the app grows beyond a handful of files.
Precompilation fits into a continuous integration process of build, test, deploy.

A: node.js is required in order to install the library using the node package manager (npm).
It is not required to run an app using angular2, only to build it.

A: For any modern JS based application, as the complexity grows, the app becomes difficult to manage.
In order to make developing and managing complex applications simpler, there are frameworks such as Angular, React etc. and they provide number of tools for the same.
These tools are linting, scaffolding, running unit test cases, starting web server for local development, minify and creating build for the production use etc.
These tools are based on NodeJS as it is JavaScript only and therefore can be customize as per developers needs.
And that's the reason you need Node.js for Angular2 development.


text:
Q: Problems with encoding in PHP functions I am trying to build an URL from a string, that I get with webcrawler. I have managed to create a crawler, but I can't make an URL string... I have managed to find out that PHP function preg_match_all messes up my result. This is what I have:
preg_match_all('/"([^"]+)"/', $str, $matches);
foreach ($matches[1] as $value) {
     $termsArray[] = $this->createUrl($value);
}

The preg_match_all function returns the correct string but, I guess, the encoding is wrong... And the createUrl function looks lite this:
private function createLikitUrl($term)
    {
    $ltSymbolsArray = array(
              'a1' => 'ą',
              'c2' => 'č',
              'e1' => 'ę',
              'e2' => 'ė',
              'i1' => 'į',
              's2' => 'š',
              'u1' => 'ų',
              'u2' => 'ū',
              'z2' => 'ž',
              '_' => ' '
          );
          $chars = preg_split("//u", $term, -1, PREG_SPLIT_NO_EMPTY);
          $urlStr = '';
          foreach ($chars as $value) {
            foreach ($ltSymbolsArray as $key => $replacement) {
              if ($value == $replacement) {
                $value = $key;
              }
            }
            $urlStr .= $value;
          }
}

The problem is that preg_split returns the same string that I pass as $term variable when preg_match_all is used with a string that has multibyte symbols. If I pass a string to the createUrl function without using preg_match_all, then it works perfectly. My guess is that I am missing unicode modifier in preg_match_all pattern, but I have hard time on writting regular expressions.
Anny help would be apreciated.

A: Not sure I understand your request, but I tried your script and it works pretty fine, except that you need to add a return $urlStr; at the end of the function.
And it has to be renamed createUrl.

A: I finnaly found a solution. If anyone will come across to this problem, this should help. As I thought, there was a problem with encoding. I just added one line of code before the preg_match_all that solved the problem:
$matches = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-13');

Cheers! :)


text:
Q: Eloquent- chessboard in coffeescript I'm trying to solve the 'chessboard' problem that's originally meant for js, in coffeescript; this is the question.

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chess board. When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

a = 8
b = 8
board = ""
x = 0
y = 0

while y < a
 y = y + 1
 while x < b
  x = x + 1
  if x % 2 == 0
   board = board + "#"
  else
   board = board + " "

 print(board)

Everything seems to work fine, except the alterting of pattern by row. It currently looks like this:
" # # # #"
" # # # #"
" # # # #"
" # # # #"
" # # # #"
" # # # #"
" # # # #"
" # # # #"

But I want it to look like this.
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

A: The updated condition from @Jonas W. was correct, but you also need to reset the x and board variable in your loop:
a = 8
b = 8
board = ""
x = 0
y = 0

while y < a
 y = y + 1
 x = 0
 board = ""
 while x < b
  x = x + 1
  if (x + (y % 2)) % 2 == 1
   board = board + "#"
  else
   board = board + " "
 print(board)

but even here there's some inconsistencies with your briefing - the board variable is infact just a row. Rather than reseting it, you probably want to append a newline ("\n") character after every row is created. But that would also mean you have to de-indent your print line another level as right now it prints it out after every row is generated.
I'd suggest taking a look into Coffeescript comprehensions rather than using those while loops.

A: let a = ""
for (let i = 1; i <= 64; i++) {
    if (i % 2 == 0) {
        a += "#"
    } else (a += " ")
    if (i % 8 == 0) {
        if ((i / 8) % 2 == 0) {
            a += "\n";
        }
        else {
            a += "\n"
            a += " "
        }
    }
}
console.log(a)


text:
Q: SwiftUI Buttons meant to increment or decrement score, does so with the value of OTHER buttons almost exclusively I have five buttons in swiftUI, that are meant to increase or decrease a displayed score, based on the response to an alert with two options, triggered on button press.
When pressing the button associated with a 200 point value, and responding to the alert, will result in an increment or decrement of the score of any other button. 400, 600, 800, and 100.
The increment or decrement is always correct, if you respond that you answer the question correctly, your score will always increase, just by a random amount. Same goes for getting the quetion wrong.
'CurrentGameStatus' is just a class, with a published variable for 'score'.
struct ContentView: View {
    @State private var showingAlert = false
    @ObservedObject var gameStatus = CurrentGameStatus()

    var body: some View {
        NavigationStack {
            HStack {
                VStack {
                    ScoreHeader(gameStatus: gameStatus)

                    Button(action: { gameStatus.score = 0}) {
                        Text("Reset Score")
                    }

                    Button(action: { showingAlert = true }) { Text("200") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert) {
                            Button("Yes") { gameStatus.score += 200 }
                            Button("No") { gameStatus.score -= 200 }
                        }

                    Button(action: { showingAlert = true }) { Text("400") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert) {
                            Button("Yes") { gameStatus.score += 400 }
                            Button("No") { gameStatus.score -= 400 }
                        }

                    Button(action: { showingAlert = true }) { Text("600") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert) {
                            Button("Yes") { gameStatus.score += 600 }
                            Button("No") { gameStatus.score -= 600 }
                        }

                    Button(action: { showingAlert = true }) { Text("800") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert) {
                            Button("Yes") { gameStatus.score += 800 }
                            Button("No") { gameStatus.score -= 800 }
                        }

I've tried using environment objects, state objects, and observed objects, none achieve the desired result.

A: It looks like you're using the same boolean for all four alerts. So when you tap any of the four buttons, it's the same showingAlert state property that is being set to true. All of the alert modifiers that you have are using that value to determine if they should be presented or not. So you're actually trying to show all four alerts at the same time, but SwiftUI (or the UIAlertController behind the scenes) is only showing one of them. Try something like this:

struct ContentView: View {
    @State private var showingAlert1 = false
    @State private var showingAlert2 = false
    @State private var showingAlert3 = false
    @State private var showingAlert4 = false
    @ObservedObject var gameStatus = CurrentGameStatus()

    var body: some View {
        NavigationStack {
            HStack {
                VStack {
                    ScoreHeader(gameStatus: gameStatus)

                    Button(action: { gameStatus.score = 0}) {
                        Text("Reset Score")
                    }

                    Button(action: { showingAlert1 = true }) { Text("200") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert1) {
                            Button("Yes") { gameStatus.score += 200 }
                            Button("No") { gameStatus.score -= 200 }
                        }

                    Button(action: { showingAlert2 = true }) { Text("400") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert2) {
                            Button("Yes") { gameStatus.score += 400 }
                            Button("No") { gameStatus.score -= 400 }
                        }

                    Button(action: { showingAlert3 = true }) { Text("600") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert3) {
                            Button("Yes") { gameStatus.score += 600 }
                            Button("No") { gameStatus.score -= 600 }
                        }

                    Button(action: { showingAlert4 = true }) { Text("800") }
                        .buttonStyle(QuestionValueButtonStyle())
                        .alert("Did you get the question right?", isPresented: $showingAlert4) {
                            Button("Yes") { gameStatus.score += 800 }
                            Button("No") { gameStatus.score -= 800 }
                        }


text:
Q: How to morph two images in Android/AndEngine I want to know is their any sub-library of Andengine that can morph two different images? or in Android? I have been looking for it but i haven't found anything. Help me out...

A: There is nothing native to andengine that will do that.
To morph images, you need a bitmap manipulation library that does that:
javamorph
For example this one.
Then in andengine, you assign a texture to a Sprite, and as the bitmap updates, you will need to update the texture region.
Or, render the morph frames and make an animatedSpritetexture.


text:
Q: Growth curves in R with standard deviation I am trying to plot my data (replicate results for each strain) and i want only one line graph for each strain, this means averaged results of replicates for each strain with points along the line with error bars (error between replicate data).

If you click on the image above, it shows the plot i have so far, which displays WT and WT.1 as seperate lines and all other replicates. However, they are replicates of each strain (WT,DrsbR,DsigB) and i want them to appear as one line of mean results for each strain instead. I am using ggplot package- and melting data with reshape package, but cannot figure out how to make my replicates appear as one line together with error bars (standard deviation of mean results between replicates).
The image in black and white is something i am looking for in my graph- seperate line with points of replicate data plotted as a mean value.

library(reshape2)
melted<-melt(abs2)
print(abs2)
melted<-melt(abs2,id=1,measured=c("WT","WT.1","DsigB","DsigB.1","DrsbR","DrsbR.1"))
View(melted)
colnames(melted)<-c("Time","Strain","Values")
##line graph for melted data
melted$Time<-as.factor(melted$Time)
abs2line=ggplot(melted,aes(Time,Values))+geom_line(aes(colour=Strain,group=Strain))
abs2line+
  stat_summary(fun=mean,
               geom="point",
               aes(group=Time))+
  stat_summary(fun.data=mean_cl_boot,
               geom="errorbar",
               width=.2)+
  xlab("Time")+
  ylab("OD600")+
  theme_classic()+
  labs(title="Growth Curve of Mutant Strains")
summary(melted)
print(melted)

A: One approach is to take your melted data frame and separate out the "variable" column into "species" and "strain" using the separate() function from tidyr.  I don't have your dataset -- it is appreciated if you are able to share your dataset via dput(your.data.frame) for future questions -- so I made a dummy dataset that's similar to yours.  Here we have two "species" (red and blue) and two "strains" for each species.
df <- data.frame(
    time = seq(0, 40, by=10),
    blue = c(0:4),
    blue.1 = c(0, 1.1, 1.9, 3.1, 4.1),
    red = seq(0, 8, by=2),
    red.1 = c(0, 2.1, 4.2, 5.5, 8.2)
)

df.melt <- melt(df,
    id.vars = 'time',
    measure.vars = c('blue', 'blue.1', 'red', 'red.1'))

We can then use tidyr::separate() to separate the resulting "variable" column into a "species" column and a "strain" column.  Luckily, your data contains a "." which can be a handy character to use for the separation:
df.melt.mod <- df.melt %>%
    separate(col=variable, into=c('species', 'strain'), sep='\\.')

Note: The above code will give you a warning related to the point that "blue" and "red" do not have the "." character, thereby giving you NA for the "strain" column.  We don't care here, because we're not using that column for anything here.  In your own dataset, you can similarly not care too much.
Then, you can actually just use stat_summary() for all geoms... modify as you see fit for your own visual and thematic preference.  Note that order matters for layering, so I plot geom_line first, then geom_point, then geom_errorbar.  Also note that you can assign the group=species aesthetic in the base ggplot() call and that mapping applies to all geoms unless overwritten.
ggplot(df.melt.mod, aes(x=time, y=value, group=species)) +
    stat_summary(
        fun = mean,
        geom='line',
        aes(color=species)) +
    stat_summary(
        fun=mean,
        geom='point') +
    stat_summary(
        fun.data=mean_cl_boot,
        geom='errorbar',
        width=0.5) +
    theme_bw()


text:
Q: Identify the coordinate system of an asbuilt I got an asbuilt with coordinates of (N 4,118,589 and E 4,271,673). It's located in Los Angeles County but I have no idea what coordinate system it is. Anyone got any idea? I thought it would be state plane coordinate but it's not.
The as built doesn't specify anything about the coordinate system and it was made in 1960


text:
Q: How to work this if condition in form and codeigniter i am using this condition for check box value in codeigniter i want if $v_d value take go in 3rd condition ,and value $v_v then go in 2nd condition and if avail both value then go 1st condition.
            print_r($this->input->post());
            $id =$this->input->post('id');
            $v_v=$this->input->post('d_v');
            $v_d=$this->input->post('d_d');
            if(isset($v_d) && isset($v_v)){
                echo"hwqq";
            }
            elseif(isset($v_v)){
                echo"hello1";
            }
            elseif(isset($v_d)){
                echo"he2";
            }

HTML CODE iS THIS
<form action="<?php base_url()?>index.php/index/home_email_update" method="POST">
 <input  type="hidden" name="id" value="<?php echo $id; ?>"/>

<?php echo $msg;?>

 <?php if($f['subscription_discount_voucher']== 1){?>

<input type="checkbox"  name="d_v"  value="0" id="textfield"> Unsubscribe from Discount Voucher Emails.

 <?php }else{?>

<input type="checkbox"  name="d_v"  value="1" id="textfield"> Subscribe from Discount Voucher Emails.

<?php }
if($f['subscribe_daily_deal']==1){ ?>

<input type="checkbox"  name="d_d" value="0" id="textfield"> Unsubscribe from Daily Deal Emails.

<?php } else{?>

<input type="checkbox"  name="d_d" value="1" id="textfield"> Subscribe from Daily Deal Emails.

<?php }?>

<button type="submit" class="submit_new">Change</button>

</form>

A: Try this,
$id =$this->input->post('id');
$v_v=$this->input->post('d_v');
$v_d=$this->input->post('d_d');

if(isset($v_d) && !isset($v_v)){
    echo "hwqq";
}
else if(!isset($v_d) && isset($v_v)){
    echo "hello1"
}
else if(isset($v_d) && isset($v_v)){
    echo "he2";
}

A: Since $this->input->post() returns FALSE if there aren't any matches in the $_POST superglobal, isset check is not going to be an appropriate check here.
Instead you could try using empty:
if(!empty($v_d) && !empty($v_v)){
  echo"hwqq";
}
elseif(!empty($v_v)){
  echo"hello1";
}
elseif(!empty($v_d)){
  echo"he2";
}

Please make sure to check Return values of empty for the list of things considered empty.


text:
Q: Integrating Line Style into MA/EMA Trend Line Wondering if I could get a little help integrating a line style into an MA/EMA script. The top portion is a direct pull from tradingviews help section on how to style a trend line.
//@version=4
study(title="Set line style with input", overlay=true)

// STEP 1. Make the input with pull-down menu
styleOption = input(title="Line Style", type=input.string,
     options=["solid (─)", "dotted (┈)", "dashed (╌)",
     "arrow left (←)", "arrow right (→)", "arrows both (↔)"],
     defval="solid (─)")

// STEP 2. Convert the input to a proper line style value
lineStyle = styleOption == "dotted (┈)" ? line.style_dotted :
     styleOption == "dashed (╌)" ? line.style_dashed :
     styleOption == "arrow left (←)" ? line.style_arrow_left :
     styleOption == "arrow right (→)" ? line.style_arrow_right :
     styleOption == "arrows both (↔)" ? line.style_arrow_both :
         line.style_solid

// STEP 3. Use the input option to set the line's style
if barstate.islastconfirmedhistory
    // Create a new line and immediately set its style
    line.new(x1=bar_index[55], y1=close[55],
         x2=bar_index, y2=close, width=4, color=color.blue,
         style=lineStyle)

    // Or make a line, and then change its style
    myLine = line.new(x1=bar_index[35], y1=close[35],
         x2=bar_index, y2=close, width=4, color=color.orange)

    line.set_style(id=myLine, style=lineStyle)

// EMA Example Need to Integreate Above style
len1 = input(21, minval=1, title="EMA 1")
src1 = input(close, title="EMA 1 source")
plot(ema(src1, len1), color=#8b0000, title="EMA 1",linewidth=1)

A: you can not use the below with plot funtion. The below can be used with line, hline function to draw horizontal and vertical lines.
styleOption = input(title="Line Style", type=input.string,
     options=["solid (─)", "dotted (┈)", "dashed (╌)",
     "arrow left (←)", "arrow right (→)", "arrows both (↔)"],
     defval="solid (─)")

// STEP 2. Convert the input to a proper line style value
lineStyle = styleOption == "dotted (┈)" ? line.style_dotted :
     styleOption == "dashed (╌)" ? line.style_dashed :
     styleOption == "arrow left (←)" ? line.style_arrow_left :
     styleOption == "arrow right (→)" ? line.style_arrow_right :
     styleOption == "arrows both (↔)" ? line.style_arrow_both :
         line.style_solid


text:
Q: live-feed shape detection TypeError The problem found by the Spyder@Anaconda IDE is shown as below:

File "C:/Users/zhiyong/Desktop/Y3_S2/programming/blue_tri_det.py", line 91, in
      cv2.drawContours(roi, shape_contour, -1, (0, 255, 0), 3, (-1, 2))
TypeError: an integer is required

And, it was working fine when I didn't place any blue triangle at the front of the webcam, but the moment I pasted one in front of it, the whole detection code went down.
def run(image, c):
    # convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    # if the shape is a triangle, it will have 3 vertices
    if len(approx) == 3:
        shape = "triangle"
        print(shape)

        # blur and threshold the image
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)

        # find the contours in the thresholded image
        (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                 cv2.CHAIN_APPROX_SIMPLE)

        # if no contours were found, return None
        if len(cnts) == 0:
            return None

        # otherwise, sort the contours by area and compute the rotated
        # bounding box of the largest contour
        c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
        rect = cv2.minAreaRect(c)
        box = np.int0(cv2.cv.BoxPoints(rect))

    else:
        shape = "No triangle is detected"
        print(shape)

    # return the bounding box of the barcode
    return box

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help = "path to the (optional) video file")
args = vars(ap.parse_args())

# if the video path was not supplied, grab the reference to the
# camera
if not args.get("video", False):
    camera = cv2.VideoCapture(0)

# otherwise, load the video
else:
    camera = cv2.VideoCapture(args["video"])

# keep looping over the frames
while True:
    # grab the current frame
    (grabbed, frame) = camera.read()

    # check to see if we have reached the end of the
    # video
    if not grabbed:
        break

    # detect the barcode in the image
    box = run(frame, c="unidentified")

    # if a barcode was found, draw a bounding box on the frame
    cv2.drawContours(frame, [box], -1, (0, 255, 0), 3, (-1,2))

    # show the frame and record if the user presses a key
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    # if the 'q' key is pressed, stop the loop
    if key == ord("q"):
        break

# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()


text:
Q: System.Net mail settings using Network Solutions hosted email I am trying to use my email service through Network Solutions (NetSol) so that emails sent via the application come from our domains service@ourdomain address.
I cannot seem to make it work, and I am not sure it is even doable since its a webmail service which I can access in a browser using a url like http://mail.ourdomain.com.
According to their site, the smtp settings can be found here
NetSol smtp
Using that information I set up my mail settings as follows
<mailSettings>
  <smtp deliveryMethod="Network">
    <network host="smtp.ourdomain.com" port="587" userName="service@ourdomain.com" password="xxxxxxxx" enableSsl="true" />
  </smtp>
</mailSettings>

I know the password is correct as I'm able to login to my mail in the webbrowser so I don't believe its a credentials error although the error in the method is erring on the credential piece.
private async Task SendMailMessageAsync(MailMessage msg)
    {
        var acct = Username;
        var pwd = Password;
        msg.IsBodyHtml = true;

        using (var mailClient = new SmtpClient())
        {
            if (acct != string.Empty && pwd != string.Empty)
            {
                var credentials = new NetworkCredential(acct, pwd);
                mailClient.Credentials = credentials; //ERRING HERE
            }
            await mailClient.SendMailAsync(msg);
        }
    }

Is anyone familiar with the proper setup for NetSol professional email?
UPDATE:
For some reason, my code edit in the answer I accepted wasn't accepted. So here is the code, in working order based on the comments in the accepted answer.
public void SendNetSolEmail()
    {
        var sender = "whatever@yourdomain.com";
        var pass = "yourpassword";
        var mailMessage = new MailMessage(sender, "sendto_emailaddress", "Hi there", "This method works fine!");
        var mailClient = new SmtpClient("mail.yourdomain.com", 587)
        {
            Credentials = new NetworkCredential(sender,pass),
            EnableSsl = false,  //important for Network Solutions mail
            DeliveryMethod = SmtpDeliveryMethod.Network
        };
        mailClient.Send(mailMessage);
    }

A: A simple working example of connecting to NetSol's smtp
System.Net.Mail.SmtpClient mailMsg = new System.Net.Mail.SmtpClient("mail.domain.com", 587);
mailMsg.Credentials = new System.Net.NetworkCredential("username@domain.com", "password");
mailMsg.SendMailAsync("username@domain.com", "someone.somewhere@somedomain.com", "Hi Someone", "Body of the email");

and the last note as I see you have ssl enabled; Here it is direct from NetSol:
Note - Make sure you are not chosing and SSL type, this option should be turned off, or "None" should be selected.


text:
Q: Python: Maximum recursion depth exceeded I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node.
here is the error:
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored

RuntimeError: maximum recursion depth exceeded while calling a Python object
Exception AttributeError: "'DictCursor' object has no attribute 'connection'" in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879776c>> ignored

Method that I call to get sql results:
def returnCategoryQuery(query, variables={}):
    cursor = db.cursor(cursors.DictCursor);
    catResults = [];
    try:
        cursor.execute(query, variables);
        for categoryRow in cursor.fetchall():
            catResults.append(categoryRow['cl_to']);
        return catResults;
    except Exception, e:
        traceback.print_exc();

I actually don't have any issue with the above method but I put it anyways to give proper overview of the question.
Recursion Code:
def leaves(first, path=[]):
    if first:
        for elem in first:
            if elem.lower() != 'someString'.lower():
                if elem not in path:
                    queryVariable = {'title': elem}
                    for sublist in leaves(returnCategoryQuery(categoryQuery, variables=queryVariable)):
                        path.append(sublist)
                        yield sublist
                    yield elem

Calling the recursive function
for key, value in idTitleDictionary.iteritems():
    for startCategory in value[0]:
        print startCategory + " ==== Start Category";
        categoryResults = [];
        try:
            categoryRow = "";
            baseCategoryTree[startCategory] = [];
            #print categoryQuery % {'title': startCategory};
            cursor.execute(categoryQuery, {'title': startCategory});
            done = False;
            while not done:
                categoryRow = cursor.fetchone();
                if not categoryRow:
                    done = True;
                    continue;
                rowValue = categoryRow['cl_to'];
                categoryResults.append(rowValue);
        except Exception, e:
            traceback.print_exc();
        try:
            print "Printing depth " + str(depth);
            baseCategoryTree[startCategory].append(leaves(categoryResults))
        except Exception, e:
            traceback.print_exc();

Code to print the dictionary,
print "---Printing-------"
for key, value in baseCategoryTree.iteritems():
    print key,
    for elem in value[0]:
        print elem + ',';
    raw_input("Press Enter to continue...")
    print

If the recursion is too deep I should be getting the error when I call my recursion function, but when I get this error when I print the dictionary.

A: You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.


text:
Q: Return multiple elements from a function number property Is there a way i can return multiple elements from a function based off a number property that it ingests? For example: I have an element of a coin, which is just a

" and I'd like to have a function where I can say {displayCoins(5)}, and the param it takes is the number of coins to return.
What I've tried so far is the following
const displayCoins = (numberOfCoins) => {
  let elCoin = document.createElement('div')
  elCoin.className = "coin"
  return elCoin * numberOfCoins
}

Thank you

A: If you want to return multiple elements you can return an array of them. You don't need to create DOM elements manually with document.createElement('div'), you can simply create them, or template them specifically, in JSX.
const displayCoins = (numberOfCoins) => {
  return [...Array(numberOfCoins).keys()].map(el => (

  ));
}


text:
Q: Is it possible to customize swarm port? If so, how to do this? according to docker doc:
The following ports must be available. On some systems, these ports are open by default.
TCP port 2377 for cluster management communications
TCP and UDP port 7946 for communication among nodes
UDP port 4789 for overlay network traffic
so if these 3 default ports are not avaiavle on hosts, how to customized these ports?

A: The following options are available in 19.03 (just released):
$ docker swarm init --help

Usage:  docker swarm init [OPTIONS]

Initialize a swarm

Options:
      --advertise-addr string                  Advertised address (format: <ip|interface>[:port])
      --autolock                               Enable manager autolocking (requiring an unlock key to start a stopped manager)
      --availability string                    Availability of the node ("active"|"pause"|"drain") (default "active")
      --cert-expiry duration                   Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s)
      --data-path-addr string                  Address or interface to use for data path traffic (format: <ip|interface>)
      --data-path-port uint32                  Port number to use for data path traffic (1024 - 49151). If no value is set or is set to 0, the default port (4789) is used.
      --default-addr-pool ipNetSlice           default address pool in CIDR format (default [])
      --default-addr-pool-mask-length uint32   default address pool subnet mask length (default 24)
      --dispatcher-heartbeat duration          Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s)
      --external-ca external-ca                Specifications of one or more certificate signing endpoints
      --force-new-cluster                      Force create a new cluster from current state
      --listen-addr node-addr                  Listen address (format: <ip|interface>[:port]) (default 0.0.0.0:2377)
      --max-snapshots uint                     Number of additional Raft snapshots to retain
      --snapshot-interval uint                 Number of log entries between Raft snapshots (default 10000)
      --task-history-limit int                 Task history retention limit (default 5)

To change the listening port on 2377 and the VXLAN port on 4789, you should be able to run something like:
docker swarm init --listen-addr 0.0.0.0:3377 --data-path-port 5789

I do not believe 7946 is configurable yet.

When joining other nodes to the swarm, you have the following options:
$ docker swarm join --help

Usage:  docker swarm join [OPTIONS] HOST:PORT

Join a swarm as a node and/or manager

Options:
      --advertise-addr string   Advertised address (format: <ip|interface>[:port])
      --availability string     Availability of the node ("active"|"pause"|"drain") (default "active")
      --data-path-addr string   Address or interface to use for data path traffic (format: <ip|interface>)
      --listen-addr node-addr   Listen address (format: <ip|interface>[:port]) (default 0.0.0.0:2377)
      --token string            Token for entry into the swarm

That lets you adjust the listener address/port. I don't know if data-path-port is a global setting in the entire swarm, that feature was only released GA an hour ago, so it will need some testing to understand how it behaves.

From your comment:

I'd like to know if the docker community will consider to make 7946 configurable

Docker is open source, so you are free to submit PR's to moby/moby, libnetwork, and/or swarmkit. Not sure which repo specifically covers this implementation detail.