text:
Q: Anonymous type and tuple What is the difference between anonymous type and tuple?

A: Another point in favor of anonymous types would be that you can easily have more than 8 properties. While this is doable using tuples, it's not so pretty.
var tuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9)); //and so on

or write your own tuple classes.

An interesting similarity to note is that both tuples and anonymous types give you immutability and equality comparability (both overrides Equals and GetHashCode) based on the properties by default.

A: Just a little update to this answer since C# 7 is out in the wild. Tuples have super powers now and can sometimes replace anonymous types and classes. Take for example this method that accepts and returns tuples with named properties.
To help illustrate what is possible, the Whatever function transforms the input shape and values.
void Main()
{
    var tupleInput = (Neat: 123, Cool: true);
    var tupleOutput = Whatever(tupleInput);
    Debug.Assert(tupleOutput.Something == 133);
    Debug.Assert(tupleOutput.Another == "True");
}

(int Something, string Another) Whatever((int Neat, bool Cool) data)
{
    return (Something: data.Neat + 10, Another: data.Cool.ToString());
}

That's cool.

A: A tuple is not an anonymous type, it's a named type.  You can use it as a return type or method argument.  This code is valid:
Tuple<int, string> GetTuple()
{
    return Tuple.Create(1, "Bob");
}

You can't do this with an anonymous type, you would have to return System.Object instead.  Typically, you end up having to use Reflection on these objects (or dynamic in .NET 4) in order to obtain the values of individual properties.
Also, as Brian mentions, the property names on a Tuple are fixed - they're always Item1, Item2, Item3 and so on, whereas with an anonymous type you get to choose the names.  If you write:
var x = new { ID = 1, Name = "Bob" }

Then the anonymous type actually has ID and Name properties.  But if you write:
Tuple.Create(1, "Bob")

Then the resulting tuple just has properties Item1 and Item2.

A: Anonymous types have property names which carry more information, for tuples you don't have this.  You can't use anonymous types as return values and parameters though and you can with tuples.
An example of when a tuple is nice is when you want to return multiple values.  @Petar Minchev mentions this link which gives a good example.
You may want a Find() method that returns both an index and the value.   Another example would be the position in a 2d or 3d plane.

A: Don't forget ValueTuple :)
Key Differences of the three:

Name
Access modifier
Type
Custom member name
Deconstruction support
Expression tree support

Anonymous types
internal
class
✔
❌
✔

Tuple
public
class
❌
❌
✔

ValueTuple
public
struct
✔
✔
❌

Source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/choosing-between-anonymous-and-tuple


text:
Q: Errors importing stats module from SciPy I'm trying to use some of the functions available here
http://www.scipy.org/doc/api_docs/SciPy.stats.stats.html
but I can only seem to get access to some of them.  For instance after I do from scipy import stats I can do something like stats.gmean([3,4]) to get the geometric mean, but when I try stats.samplestd([3,4]) I get an error that says the module has no attribute samplestd.
Any help would be greatly appreciated.
I'm running enthought's python distribution if that helps.
Thanks

A: scipy.stats.samplestd() was deprecated in SciPy 0.8 and removed in SciPy 0.9.  Probably, you are using version 0.9.  You should use numpy.std() instead.
Be sure to use the SciPy docs matching the version you use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Http status 404 not found error in eclipse I used eclipse and tomcat and created a dynamic web project following this tutorial:
https://o7planning.org/en/10169/java-servlet-tutorial
I followed all the steps until running the code for the first time to display 'Hello, World!' on a webpage, but it gave the following error. I have added index.html properly.
What could be the issue? Yesterday I created another dynamic project in the same workspace that the simple project was run it, but it's not working either. Could it be a port issue?
HTTP Status 404 – Not Found
Type Status Report
Message /ServletFirstTutorial/
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.14
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   <display-name>ServletFirstTutorial</display-name>

   <welcome-file-list>
       <welcome-file>index.html</welcome-file>
       <welcome-file>index.htm</welcome-file>
       <welcome-file>index.jsp</welcome-file>
       <welcome-file>default.html</welcome-file>
       <welcome-file>default.htm</welcome-file>
       <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>

</web-app>


text:
Q: What is direct interaction, if exist, between gluons and pions? Gluons mediate the strong force between quarks. Pions mediate the nuclear force or nucleon-nucleon interaction or residual strong force.
I had thought of some scalar bosons for my idea because if I'm not mistaken between the gluon and the pion it should occur a particular transformation properties under Lorentz transformation that is, instead, a scalar boson.
I remember that force between quarks is non-abelian force (whose substrate can be thought of in terms of non-abelian Lie groups) but I'm not sure.
I want to know math model or if exist something that explain a possible direct interaction between gluons and pions because I want to understand what kind of mathematical surface/manifold/variety could describe the "surface" of the proton because proton surface remember me a sort interface and separation between gluons and pions a sort of interphase or phase transition but

topological order is a kind of order in the zero-temperature phase of matter (also known as quantum matter).
  States with different topological orders (or different patterns of long range entanglements) cannot change into each other without a phase transition.

Just for an idea

In the physical sciences, an interface is the boundary between two spatial regions occupied by different matter, or by matter in different physical states. The interface between matter and air, or matter and vacuum, is called a surface

Instead

the boundary of a subset S of a topological space X is the set of points which can be approached both from S and from the outside of S. More precisely, it is the set of points in the closure of S not belonging to the interior of S

A: Having obnunciated any expectations of "direct interactions" or topological concepts you might well be proposing as candidates for insight here, I would steer you to the more mainstream buzzwords "the chiral symmetry breaking transition (or interface)" for further study.
The math is highly elaborate and untypical indirect, and the best experts on it are nuclear-particle physicists.
As you indicated, the nonabelian nature of gluon interactions in QCD induces two incompletely understood mathematically, but qualitatively well described, phenomena: confinement of quarks and gluons inside hadrons, and chiral symmetry breaking (χSB), the weightiest "origin of mass".
They both occur at roughly the same distance scales, ~ a fermi, the radius of hadrons, such as the proton. Equivalently, at energies of a half a GeV. Many experts believe χSB takes place a little inside the confinement radius, so a pion and massive constituent quarks (not QCD, current ones)  picture could give insights, in a thin shell between the χSB and confinement scales. This is the last time they stood side-by side--but no gluons, as these have gelled into something nonperturbative and hard to conceive.
Inside the confinement scale, particle physicists use QCD, the theory of quarks and gluons, and lattice simulators stretch our knowledge to the edge of the confinement scale, investigating how and which hadrons form. Here, strong forces increase with distance.
Outside the confinement scale, you only have color-singlet hadrons, and the "cheapest" ones to make are the ones requiring the least energy, the light ones, the pions. These provide the main dynamo behind the binding of nuclei, but the other mesons (vector, scalar, etc...) crucially shape and modify the picture. This is firmly in the ambit of nuclear physics.
The pions are light because of their  pivotal role in χSB, so their low mass provides a notional extended "cloud" of them on the edge of the hadron, providing the residual strong nuclear forces studied by strikingly different techniques. (This made my favorite nuclear physicist describe the proton as a "marshmallow".) Such forces decrease with distance.
The above two communities of investigators interface in interesting ways, but there is no complete and stable, let alone elegant!, understanding of the interface. One could argue the millennium problemrelated to confinement hankers for such a mathematical grasp and methodology that would lead to such understanding. It is a very open question.

*

*A small caveat about your "transformation" vision: pions consist of gluons, quarks and antiquarks, arranged differently than scalar mesons, where it matters (a lot). The scalar mesons are much heavier than the pseudoscalar ones: they are basically as heavy as any other meson type. Particle physicists today cringe at the thought of a "transformation" transitioning among species, as a sought-for "Melosh transformation"  in the early 1970s, transitioning between current and constituent quarks turned out to be not only an utterly failed idea, but an insidiously counterproductive one (it basically barked up a wrong tree so aggressively it undermined subsequent understanding).


text:
Q: why do all the contacts are displayed in my Quick action?
Always all the contacts are fetched in my LWC component which is used in Account quick action even though i used below query in my Apex class
select id,name,email,Is_Primary__c from contact where AccountId=:AccountId

A snippet from HTML file
<h2> Select Contacts</h2>
              <lightning-datatable data={result} columns={columns} key-field="Id">
              </lightning-datatable>

Snippet below for JS file
//Inside export part introduced a variable for recordId by using @api decorator. It will be a public access modifier.
import { LightningElement, api,track } from 'lwc';
import showContacts from "@salesforce/apex/contactHelper.fetchcontacts";
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import DESCRIPTION_FIELD from '@salesforce/schema/Account.Description';
import ID_FIELD from '@salesforce/schema/Account.Id';

export default class RecordIdInLWC extends LightningElement {
    @track columns = [{
        label: 'Is Primary',
        fieldName: 'Is_Primary__c',
        type: 'text',
        sortable: true,
        editable:true
    },{

        label: 'Name',
        fieldName: 'Name',
        type: 'text',
        sortable: true
    },
    {
        label: 'Email',
        fieldName: 'Email',
        type: 'text',
        sortable: true
        },

    ];

    //Create a Record ID variable
    @api recordId;
    @track result;
    @api invoke() {
        console.log("+++"+this.recordId);

    }

   connectedCallback(){
        console.log("+++"+this.recordId);
        showContacts({ AccountId: this.recordId })
        .then(res => {
            if (res!=null) {
                this.result = res;
                console.log("++Result++"+JSON.stringify(this.result ));
            }
        })
         .catch(error => {
            console.log('Data fetch failed', error);
            this.error = error;
          });
}
}

where result is the value from my apex class (list of contacts) column is the track decorator definition to hold the column attributes
if i use the same component in the record page the query works fine. What should be the problem here ?


text:
Q: jsPlumb Draggable with Container Element - How to setup? How do you set up jsPlumb draggable divs, with a container div?
I have a container positioned relatively, and the divs to be draggable positioned absolutely (this is what the documentation suggestions).  The container is 100px from the top of the page. Unless I set margin-top to be -100px for the container, the drag is shifted over by 100px down. How can I fix this?

A: Fixed it.  I had a padding-top on the body element that caused that very weird error.  Takeaway:

*

*For draggable to work with jsPlumb, the container element's position should be relative, the draggable elements' position absolute, and any parent elements of the container should not have any padding.


text:
Q: Can't pass array of objects to controller by jQuery AJAX I tried to pass array of objects to controller by jQuery Ajax, but result is null in ASP.NET 5.0.
My data array is what send to controller:  regions.
Data constructor is defined in BoundingBoxModel class.
This is my ajax function:
$("body").on("click", "#onClick", function () {
            var regions = [];
            var arr = Array.prototype.slice.call(document.getElementsByClassName('ui-draggable'));
            arr.forEach((tagele) => {
                var region = {};
                region.Height = tagele.offsetHeight;
                region.Width = tagele.offsetWidth;
                region.Top = tagele.offsetTop;
                region.Left = tagele.offsetLeft;
                regions.push(region);
            });
            $.ajax({
                url: '/GenCode/Addregions',
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({'regions': regions}),
                success: function () {
                    alert("pass")
                },
                error: function (jqXhr, json, errorThrown) {
                    alert(errorThrown);
                    console.log(errorThrown);
                }
            });
        });

So this is my BoundingBoxModel:
 public class BoundingBoxModel
    {
        public int BoundingBoxId { get; set; }
        public double Top { get; set; }
        public double Left { get; set; }
        public double Height { get; set; }
        public double Width { get; set; }
    }

This is my action method. It's defined in GenCodeController.
[HttpPost]
    public IActionResult AddRegions(List<BoundingBoxModel> regions)
    {
        JsonResult result = new JsonResult(this.Json(JsonConvert.SerializeObject(regions), System.Web.Mvc.JsonRequestBehavior.AllowGet));
         return result;
    }

My result is null:

I don't understand why it's happened. Can you help me?

A: There are some issues that I can see -

*

*I am not sure if you explicitly written this logic but your region object will always have last value of arr because you declare your variable inside loop.

*If you are trying to create an array then you should declare your region variable like - var region = []; .Right now it is an object.

*You are trying to pass an object and accepting a list in webservice. Either remove the list in parameter in AddRegions service or pass a Array from ajax call.

A: I resolved my problem by deteting contentType: "application/json;charset=utf-8", line in ajax code.
Using this line make the array of region's type change to string so  when i get data in Controller problem was happened.


text:
Q: How to convert values of object with dynamic properties into array I have object like this:
titles: {
   dr: 'Dr',
   prof: 'Prof',
   profdr: 'Prof Dr'
}

How can I transform it into array like this:
['Dr', 'Prof', 'Prof Dr']

Method should be dynamic because I need it for multiple objects with different number of properties.

A: Use Object.values

const titles = {
   dr: 'Dr',
   prof: 'Prof',
   profdr: 'Prof Dr'
}
console.log(Object.values(titles));


text:
Q: I need save some picture,how can I fix that ByteArrayInputStream to FileInputStream? the request headers:
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:61425
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarysqFOqeLTqOafwiDl
Cookie:JSESSIONID=F98C35E6649DC6997616A2CCB70A946A; save=F98C35E6649DC6997616A2CCB70A946A
Host:192.168.0.105:8080
Origin:http://192.168.0.105:8080
Referer:http://192.168.0.105:8080/list
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
X-Requested-With:XMLHttpRequest

this is my code:
public boolean muilt(MultipartHttpServletRequest multiReq) throws IOException {
        Map<String, MultipartFile> map = multiReq.getFileMap();
        List<String> list = new ArrayList<>();
        for (String in : map.keySet()) {
            MultipartFile str = map.get(in);
            System.out.println(str.getSize());
            System.out.println(str.getOriginalFilename());
            if (str.getSize() != 0) {
                list.add(in + "," + url + in + ".jpg");
                FileOutputStream fos = new FileOutputStream(new File(url + in + ".jpg"));
                FileInputStream fs = (FileInputStream) str.getInputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fs.close();
            }
        }
        if (list.size() < 7){
            return false;
        }
        for (int i = 0; i < 6; ++i){
            String[] sourceStrArray = list.get(i).split(",");
            this.split(sourceStrArray[0], sourceStrArray[1]);
        }
        return true;
    }

the error code :
FileInputStream fs = (FileInputStream) str.getInputStream();

when it run, I get the problem:

java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be
  cast to java.io.FileInputStream   at
  tools.SplitPhoto.muilt(SplitPhoto.java:87)    at
  controller.HanderPhoto.photoHander(HanderPhoto.java:63)   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at
  org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

the source is a picture,I want to write it's stream to the file, how should I do?

A: MultipartFile's getInputStream() method returns an InputStream. You don't have to know what kind of InputStream it returns. As you see, it's not a FileInputStream, and that should not matter.
All you need to do is read from the InputStream returned and write to your file. You read from an InputStream the same way, whatever the concrete type of the InputStream is. That's what polymorphism is all about.
So, just remove that useless cast, and use InputSTream instead of FileInputStream.
Note that you can copy all the content of an InputStream to a file in one line of code using Files.


text:
Q: Closing WP_LINK_PAGES DIV ID w/After Argmuent In my code below I need to close the div "link_wrap" which I created with $args['before'] = '
';
When I try to paste $args['after'] = '
'; above return $args; it adds the appropriate closing div but also renders the rest of my code, which allows both previous/next links and pagination, completely useless.
How do I properly close the div while maintaining the functionality of the rest of my code?
// WP_LINK_PAGES: Add prev and next links to a numbered link list
add_filter('wp_link_pages_args', 'wp_link_pages_args_prevnext_add');

    function wp_link_pages_args_prevnext_add($args)
{
    global $page, $numpages, $more, $pagenow;

    $args['before'] = '
';
    $args['link_before'] = '';
    $args['link_after'] = '';

    if($page-1) # there is a previous page
        $args['before'] .= ' '. _wp_link_page($page-1)
            . $args['link_before'] . $args['previouspagelink']  . '' . ' '
        ;

    if ($page<$numpages) # there is a next page
        $args['after'] = ' '. _wp_link_page($page+1)
           . $args['link_before'] . $args['nextpagelink']  . ''
        ;

    return $args;

}

A: First, declare the after arg at the beginning of your code:
$args['before'] = '
';
$args['after']  = '
';

When there is a next page, the arg is overwritten, so you'll have to add the closing tag at the end:
if ($page<$numpages) # there is a next page
    $args['after'] = ' '. _wp_link_page($page+1)
       . $args['link_before'] . $args['nextpagelink']  . '
'
    ;


text:
Q: Javascript Bradley adaptive thresholding implementation I have been trying to implement Bradley Adaptive thresholding. I know there is a python code in one of the stack overflow questions. But i am struggling to implement the same in JS by following that. Can anyone please help me? So far my code is:
function computeAdaptiveThreshold (imagetest,imageWidth,imageHeight,callback)
{

    var   size = imageWidth*imageHeight*4;
    var  s = imageWidth/8;
    var s2=s>>1;
    var t=0.15;
    var it=1.0-t;
    var i,j,diff,x1,y1,x2,y2,ind1,ind2,ind3;
    var sum=0;
    var ind=0;
    var integralImg = [];

    var canvas = document.createElement('canvas');
    var bin = canvas.getContext('2d').createImageData(imageWidth, imageHeight);

    for(i=0;i<imageWidth;i++)
    {
        sum = 0;

        for(j=0;j<imageHeight;j++)
        {
            index = i *imageHeight + j;
            sum += imagetest.data[index];

            if(i== 0)
            {
                integralImg[index] = sum;
            }
            else
            {
                //index = (i-1) * height + j;
                integralImg[index] = integralImg[(i-1) * imageHeight + j] + sum;
            }
        }
    }

    x1=0;

    for(i=1;i<imageWidth;++i)
    {
        sum=0;
        ind=i;
        ind3=ind-s2;
        if(i>s)
        {
            x1=i-s;
        }
        diff=i-x1;
        for(j=0;j<imageHeight;++j)
        {
            sum+=imagetest.data[ind];// & 0xFF;
            integralImg[ind] = integralImg[(ind-1)]+sum;
            ind+=imageWidth;
            if(i<s2)continue;
            if(j<s2)continue;
            y1=(j<s ? 0 : j-s);
            ind1=y1*imageWidth;
            ind2=j*imageWidth;

            if (((imagetest.data[ind3])*(diff * (j - y1))) < ((integralImg[(ind2 + i)] - integralImg[(ind1 + i)] - integralImg[(ind2 + x1)] + integralImg[(ind1 + x1)])*it)) {
                bin.data[ind3] = 0;
            } else {
                bin.data[ind3] = 255;
            }
            ind3 += imageWidth;
        }
    }

    y1 = 0;
    for( j = 0; j < imageHeight; ++j )
    {
        i = 0;
        y2 =imageHeight- 1;
        if( j <imageHeight- s2 )
        {
            i = imageWidth - s2;
            y2 = j + s2;
        }

        ind = j * imageWidth + i;
        if( j > s2 ) y1 = j - s2;
        ind1 = y1 * imageWidth;
        ind2 = y2 * imageWidth;
        diff = y2 - y1;
        for( ; i < imageWidth; ++i, ++ind )
        {

            x1 = ( i < s2 ? 0 : i - s2);
            x2 = i + s2;

            // check the border
            if (x2 >= imageWidth) x2 = imageWidth - 1;

            if (((imagetest.data[ind])*((x2 - x1) * diff)) < ((integralImg[(ind2 + x2)] - integralImg[(ind1 + x2)] - integralImg[(ind2 + x1)] + integralImg[(ind1 + x1)])*it)) {
                bin.data[ind] = 0;
            } else {
                bin.data[ind] = 255;
            }
        }
    }

    callback(bin);`

I am getting very bad images. I should say i cannot call it as a image.

A: I think your first effort should be to refactor your code : it will be much easier to handle the index.
Then you'll see that you have issues with your indexes : an image -even a gray one- is an RGBA Array, meaning 4 bytes = 32 bits per pixel.
You could handle this by doing a conversion RGBA-> b&W image, then thresholding, then doing b&w -> RGBA back.
...Or handle the RGBA components as you go. Notice that here you only want to output black or white, so you can create an Int32 view on the array, and write at once R,G,B,A for each pixels.
So some code (working here : http://jsfiddle.net/gamealchemist/3zuopz19/8/ ) :
function computeAdaptiveThreshold(sourceImageData, ratio, callback) {
    var integral = buildIntegral_Gray(sourceImageData);

    var width = sourceImageData.width;
    var height = sourceImageData.height;
    var s = width >> 4; // in fact it's s/2, but since we never use s...

    var sourceData = sourceImageData.data;
    var result = createImageData(width, height);
    var resultData = result.data;
    var resultData32 = new Uint32Array(resultData.buffer);

    var x = 0,
        y = 0,
        lineIndex = 0;

    for (y = 0; y < height; y++, lineIndex += width) {
        for (x = 0; x < width; x++) {

            var value = sourceData[(lineIndex + x) << 2];
            var x1 = Math.max(x - s, 0);
            var y1 = Math.max(y - s, 0);
            var x2 = Math.min(x + s, width - 1);
            var y2 = Math.min(y + s, height - 1);
            var area = (x2 - x1 + 1) * (y2 - y1 + 1);
            var localIntegral = getIntegralAt(integral, width, x1, y1, x2, y2);
            if (value * area > localIntegral * ratio) {
                resultData32[lineIndex + x] = 0xFFFFFFFF;
            } else {
                resultData32[lineIndex + x] = 0xFF000000;
            }
        }
    }
    return result;
}

function createImageData(width, height) {
    var canvas = document.createElement('canvas');
    return canvas.getContext('2d').createImageData(width, height);
}

function buildIntegral_Gray(sourceImageData) {
    var sourceData = sourceImageData.data;
    var width = sourceImageData.width;
    var height = sourceImageData.height;
    // should it be Int64 Array ??
    // Sure for big images
    var integral = new Int32Array(width * height)
    // ... for loop
    var x = 0,
        y = 0,
        lineIndex = 0,
        sum = 0;
    for (x = 0; x < width; x++) {
        sum += sourceData[x << 2];
        integral[x] = sum;
    }

    for (y = 1, lineIndex = width; y < height; y++, lineIndex += width) {
        sum = 0;
        for (x = 0; x < width; x++) {
            sum += sourceData[(lineIndex + x) << 2];
            integral[lineIndex + x] = integral[lineIndex - width + x] + sum;
        }
    }
    return integral;
}

function getIntegralAt(integral, width, x1, y1, x2, y2) {
    var result = integral[x2 + y2 * width];
    if (y1 > 0) {
        result -= integral[x2 + (y1 - 1) * width];
        if (x1 > 0) {
            result += integral[(x1 - 1) + (y1 - 1) * width];
        }
    }
    if (x1 > 0) {
        result -= integral[(x1 - 1) + (y2) * width];
    }
    return result;
}


text:
Q: Launching the whole test suite with Appium Now I am trying to automate hybrid mobile app using Appium.
For now I run test suites on android emulators, using GenyMotion or Android SDK emulators, but I have problems with both.
When I launch my tests one by one, one at a time - everything is OK. Sometimes everything is OK even while launching them 2 or 3 at one time.
But when I try to launch the whole test suite (the whole class with test methods) - problems with Appium sessions occur.
My base settings:
public class BaseAppTest {
    protected AppiumDriver driver;

    @BeforeMethod
    public void before() throws Exception
    {
        File appDir = new File("D:\\Build\\");
        File app = new File(appDir, "2015-06-10_13-09-03_amt-en_Development_234.apk");

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "192.168.56.101:5555");
        capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Appium");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "4.4");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
        capabilities.setCapability("autoWebviewTimeout", 5000);
        capabilities.setCapability("app", app.getAbsolutePath());

        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);

        Set<String> contextNames = driver.getContextHandles();
        driver.context(contextNames.toArray()[1].toString()); // set context to WEBVIEW_1
        WebDriverRunner.setWebDriver(driver);

    }

    @AfterMethod
    public void afterMethod()
    {
       driver.quit();
    }
}

Inside tests I use Selenide, also use navigation from URL to URL and LocaleStorage injections:
public class WGCTest extends BaseAppTest {

    @BeforeMethod
    public void before() throws Exception {
        super.before();
        Thread.sleep(2000);
        //driver.navigate().to(BaseSelectors.URL);
        LocalStorageInjector.clearStorage(getWebDriver());
        open(BaseSelectors.URL);
    }

}

And testSuite:
@BeforeMethod
public void before() throws Exception {
        super.before();
        Injections.injectionWeek0(getWebDriver());
        open(WGCSelectors.URL);
        //driver.navigate().to(WGCSelectors.URL);
        //WebDriverRunner.setWebDriver(driver);
    }

    @Test
    @Features(MyFeatures.WGC)
    @Stories("Clicking links")
    public static void clickingHowItWorksLink()
    {
        WGCTestMethods2.clickHowItWorksLink(weight85, weight300, feet5, inches0);
    }

    @Test
    @Features(MyFeatures.WGC)
    @Stories("Checking default structure")
    public static void checkDefaultStructure()
    {
        WGCTestMethods2.defaultStructureChecking();
    }

    @Test
    @Features(MyFeatures.WGC)
    @Stories("Filling fields and checking saving")
    public static void settingPreWeightFieldAndCheckChangesGotSaved() {
        WGCTestMethods2.settingPreWeightField(weight85);
    }

I think something is wrong is settings or annotations, cause each tests is OK separately... But what is wrong?
Please help find my mistakes! Thank you!
Exception:
     org.openqa.selenium.remote.SessionNotFoundException:
Command duration or timeout: 3 milliseconds
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'KOZLOVA7', ip: '192.168.2.87', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{app=D:\Build\2015-06-10_13-09-03_amt-en_Development_234.apk, networkConnectionEnabled=true, autoWebviewTimeout=5000, warnings={}, databaseEnabled=false, deviceName=emulator-5554, platform=LINUX, desired={app=D:\Build\2015-06-10_13-09-03_amt-en_Development_234.apk, autoWebviewTimeout=5000, platformVersion=4.4, automationName=Appium, platformName=Android, deviceName=emulator-5554}, platformVersion=4.4.4, webStorageEnabled=false, locationContextEnabled=false, automationName=Appium, browserName=Android, takesScreenshot=true, javascriptEnabled=true, platformName=Android}]
Session ID: 69af8a8f-83af-4c46-a7d1-56d6d4d31cf9
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:162)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:180)
    at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:508)
    at utils.LocalStorageInjector.LocalStorageInjector.clearStorage(LocalStorageInjector.java:21)
    at AppTests.BaseTests.WGCTest.before(WGCTest.java:17)
    at AppTests.WGCTestSuite02.before(WGCTestSuite02.java:36)

A: You are getting this error because already a session exists for the same parameters.
Please change your annotation from @BeforeMethod to @BeforeTest and the same for @AfterTest. In this way the before and after steps will be provided once time before/after the whole test suite.


text:
Q: Connect Sys as Sysdba : Insufficient privileges I'm trying to connect to an Oracle database using SQL Developper as Sys DBA but I'm receiving the error : ORA 1031 : Insufficient Privileges.
I'm sure the password is correct because I'm able to connect to the same database using SQLPlus :

Does anyone know how to solve that please ?
Thanks

A: change role to be sysdba instead of default in sqldeveloper

A: Check if the parameter REMOTE_LOGIN_PASSWORDFILE is set to exclusive. This is necessary to login AS SYSDBA from SQL developer :
SQL> show parameter remote_login_passwordfile

To change it :
SQL> ALTER SYSTEM SET REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE SCOPE=SPFILE;

A: Role(par defaut) - role(sysdba) or sysoper


text:
Q: ERROR : Caused by: java.lang.IllegalArgumentException: Relationship null doesn't start with this part /ppt/slides/slide3.xml I'm working with apache poi xslf to export ppt file.
First, I have a template set with 3 slides : title slide, summary slide, and third slide
I duplicate the 3rd slide (i have it as a template) in order to copy many data/graphics as I have in database.
So in order to do that :
XMLSlideShow slideShow = new XMLSlideShow(dlfile.getContentStream());
XSLFSlide[] slides = slideShow.getSlides();
XSLFSlide createdSlide = slideShow.createSlide(slides[2].getSlideLayout());
//get content from slide to createdslide
createdSlide.importContent(slides[2]);
//... add data to created slide

I have an error at line : createdSlide.importContent(slides[2]);
Caused by: java.lang.IllegalArgumentException: Relationship null doesn't start with this part /ppt/slides/slide3.xml
    at org.apache.poi.openxml4j.opc.PackagePart.getRelatedPart(PackagePart.java:468)
    at org.apache.poi.xslf.usermodel.XSLFSheet.importBlip(XSLFSheet.java:521)
    at org.apache.poi.xslf.usermodel.XSLFSlide.importContent(XSLFSlide.java:235)

P.S : this code works just fine with another tempalte.
I need to use different templates based on user selection. (templates are stored in db as i'm using liferay).
I've searched for hours, but in vain!
I don't even understand what the error means.
Any links/help would appreciated.

A: The error comes from org.apache.poi.openxml4j.opc.PackagePart.getRelatedPart code line 468:
throw new IllegalArgumentException("Relationship " + rel + " doesn't start with this part " + _partName);.
The error states that rel is null. So org.apache.poi.xslf.usermodel.XSLFSheet.importBlip in code line 521:
blipPart = packagePart.getRelatedPart(blipRel);
had handed over blipRelas null. So org.apache.poi.xslf.usermodel.XSLFSlide.importContent in code line 235:
String relId = importBlip(blipId, src.getPackagePart());
had handed over blipId as null.
This is pretty clear if one of the pictures in your template in Slide 3 is not an embedded picture but a linked picture. The code:
@Override
public XSLFSlide importContent(XSLFSheet src){
    super.importContent(src);

    XSLFBackground bgShape = getBackground();
    if(bgShape != null) {
        CTBackground bg = (CTBackground)bgShape.getXmlObject();
        if(bg.isSetBgPr() && bg.getBgPr().isSetBlipFill()){
            CTBlip blip = bg.getBgPr().getBlipFill().getBlip();
            String blipId = blip.getEmbed();

            String relId = importBlip(blipId, src.getPackagePart());
            blip.setEmbed(relId);
        }
    }
    return this;
}

consideres only embedded blip data.
From your code lines I can see that you are using apache poi version 3.9. But as far as I see in current versions this had not changed until now. Only embedded bilp data will be considered.
So have a look at your template and make sure that all pictures are embedded and not linked.


text:
Q: htaccess: Access-Control-Allow-Origin wildcard for TLD? (.com, .org...) Is there a wildcard for any top level domain in .htaccess for Access-Control-Allow-Origin?
I want to allow all top level domains (and any subdomain) of *.example.*.
So: example.com, example.org, any.example.com ...
Currently it works with:
SetEnvIf Origin ^(https?://.+\.example\.com(?::\d{1,5})?|https?://.+\.example\.org(?::\d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

A: You can't specify a partial wildcard in the response.
You need to write code which examines the Origin request header, checks that it is acceptable and then echos it back in the response.


text:
Q: Is it possible to reference the most recently modified file in a command line argument? I frequently download PDF files with heinous numeric file names from my browser.  These automatically go into ~/Downloads.  Ideally I would like to just be able to open these files with:
evince "the most recently modified file"

without having to open ~/Downloads to find the file name.
Is there a simple way to specify "the most recently modified file" in bash?
NOTE: I know that it is possible to do this, but ideally I am looking for a solution that would be simpler than ls -t'ing ~/Downloads to check the name.

A: This is a more correct and robust approach than ls -t, at the cost of some additional complexity.
Setup
Add a short shell script (code below) to your $PATH.  ~/bin is a good place for it.
Remember to make sure

*

*the script is executable chmod +x ~/bin/script_name

*~/bin is in your $PATH
Usage
Pass the command you want to run on the newest file in ~/Download to last_download.
Examples
Assuming you named the script last_download

*

*last_download (no arguments): runs evince, the default command, on the newest file in ~/Downloads

*last_download mplayer: runs mplayer on the newest file in ~/Downloads

*last_download cp -t ~/Desktop: copies the newest file in ~/Downloads to ~/Desktop
Code
#!/bin/sh
# Usage: last_download [cmd [options]...]

newest=
dir=~/Downloads

# default command
if [ $# -eq 0 ]; then
        set -- evince;
fi

# find newest file
for f in "$dir"/*; do
        if [ -z "$newest" ] || [ "$f" -nt "$newest" ]; then
                newest="$f"
        fi
done
if ! [ -e "$newest" ]; then
        exit 1
fi

# run command on newest file
"$@" "$newest"

Note: The script only looks in ~/Download but it would not be hard to generalize it to support any directory, in which case a name change would also be warranted.

A: exec zsh
evince ~/Downloads/*.pdf(om[1])

or if you don't want to switch to zsh
cd ~/Downloads
zsh -c 'evince ./*.pdf(om[1])'

The bits between parentheses are glob qualifiers. om changes the order on globs to use the modification time rather than the name (newest first). [1] means to use only the first match.
For more information, see this answer to "How do I filter a glob in zsh".

A: You can use a modified find_date_sorted:
last_download() {
    while IFS= read -r -d '' -u 9
    do
        cut -d ' ' -f 3- <<< "$REPLY"
        break
    done 9< <(find ~/Downloads -maxdepth 1 -type f -printf '%TY-%Tm-%Td %TH:%TM:%TS %p\0' | sort -rz)
}

It'll work with any filenames. To open the file:
evince "$(last_download)"

A: evince "$(ls -t | head -n1)"

While it will handle spaces, tabs, and (I believe) printing specials, it will break if the filename contains a newline, and possibly on some other non-printing characters.

A: No, and even if there were, you couldn't be sure some system log won't usually be the most recently updated file.
Kevin's answer (he beat me to it) works if you just want to avoid manually opening ~/Downloads.


text:
Q: html form vertical textfield can some one help me creating a vertical text field. actually I want to create a email subscription form in which I want to place a text field which can only take one character per row.

A: You could use something like <textarea style="height: 5em; width: 0.8em;" ></textarea> (this will display the characters vertically). You may have to play with the height and width.

A: The writing-mode and filter properties of css can be used make a vertical effect to a textarea. Following is an example html page, using these properties is a class

<html>
<head>
<style type="text/css">
  .verticaltext {
      writing-mode: tb-rl;
      filter: flipv fliph;
  }
</style>
</head>
<body>
  <textarea class="verticaltext"/></textarea>
</body>
</html>

While reading values form the textarea you may have to split it and get each character.
You may apply this css to div elements also.


text:
Q: Call function from external javascript file with onclick so I'm seeing everyone else have no problems with this,
I included
<script type="text/javascript" src="vid.js"></script>
<input type="button" onclick="javascript: stopCall();"/>

stopCall is defined in the vid.js file and it runs fine if I call it directly inside. There is no problem with the vid.js file btw, it's working completely fine. The problem is accessing any of vid.js's functions outside of the script itself. I can't seem to call it later in any form. Can someone please help?


text:
Q: Docker Desktop for windows - Waiting for SSH to be available... getting IPV6 address Expected behavior
Docker is up and running!
Actual behavior
Waiting for SSH to be available...
Steps to reproduce the behavior
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 (from https://docs.docker.com/get-started/part4/#set-up-your-swarm)
Hi All, I'm getting "waiting for SSH to be available" when I try to create a docker machine with hyperV driver but sometimes it's working and sometimes not so I got the following logs. The only thing that changes is the version of the IP address : the creation fail with an IPV6. The instruction "networkadapters[0]).ipaddresses[0]" got IPV6 address when the machine creation is failing.
When the machine is created with no errors :
Waiting for SSH to be available...
(myvm1) DBG | [stderr =====>] :
Getting to WaitForSSH function...
(myvm1) Calling .GetSSHHostname
(myvm1) DBG | [executing ==>] : C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive ( Get-VM myvm1 ).state
(myvm1) DBG | [stdout =====>] : Running
(myvm1) DBG |
(myvm1) DBG | [stderr =====>] :
(myvm1) DBG | [executing ==>] : C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive (( Get-VM myvm1 ).networkadapters[0]).ipaddresses0 DBG | [stdout =====>] : 10.23.133.214
(myvm1) DBG |
(myvm1) DBG | [stderr =====>] :
(myvm1) Calling .GetSSHPort
(myvm1) Calling .GetSSHKeyPath
(myvm1) Calling .GetSSHKeyPath
(myvm1) Calling .GetSSHUsername
Using SSH client type: external
&{[-F /dev/null -o PasswordAuthentication=no -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=quiet -o ConnectionAttempts=3 -o ConnectTimeout=10 -o ControlMaster=no -o ControlPath=none docker@10.23.133.214 -o IdentitiesOnly=yes -i C:\Users\Toto.docker\machine\machines\myvm1\id_rsa -p 22] C:\Program Files\Git\usr\bin\ssh.exe }
About to run SSH command:
exit 0
SSH cmd err, output: :
Detecting the provisioner...

When the machine is created with error :
Waiting for SSH to be available...
Getting to WaitForSSH function...
(myvm2) Calling .GetSSHHostname
(myvm2) DBG | [executing ==>] : C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive ( Get-VM myvm2 ).state
(myvm2) DBG | [stdout =====>] : Running
(myvm2) DBG |
(myvm2) DBG | [stderr =====>] :
(myvm2) DBG | [executing ==>] : C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive (( Get-VM myvm2 ).networkadapters[0]).ipaddresses0 DBG | [stdout =====>] : fe80::215:5dff:fe84:ac46
(myvm2) DBG |
(myvm2) DBG | [stderr =====>] :
(myvm2) Calling .GetSSHPort
(myvm2) Calling .GetSSHKeyPath
(myvm2) Calling .GetSSHKeyPath
(myvm2) Calling .GetSSHUsername
Using SSH client type: external
&{[-F /dev/null -o PasswordAuthentication=no -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=quiet -o ConnectionAttempts=3 -o ConnectTimeout=10 -o ControlMaster=no -o ControlPath=none docker@fe80::215:5dff:fe84:ac46 -o IdentitiesOnly=yes -i C:\Users\Toto.docker\machine\machines\myvm2\id_rsa -p 22] C:\Program Files\Git\usr\bin\ssh.exe }
About to run SSH command:
exit 0
SSH cmd err, output: exit status 255:
Error getting ssh command 'exit 0' : ssh command error:
command : exit 0
err : exit status 255
output :
Getting to WaitForSSH function...

Information
Diagnostic ID : 64F0C90F-2963-4B91-97A4-4E8B649571E2/2017-06-14_14-40-28
Version 17.03.1-ce-win12 (12058) Channel: stable d1db126
Windows 10 Entreprise


text:
Q: $G$-sets, natural correspondence? See here.

In the category of $G$-sets, the morphisms $f:G/H\to X$ are in one-to-one correspondence with the elements of $X^H$; the correspondence sends $f$ to $f(H)$ (where the subgroup $H$, being a coset of itself, is an element of $G/H$). After checking that this correspondence is natural...

Sorry, but how do we show naturality here? It's not clear to me...

A: Let $\phi_H: \textbf{Hom}_{G-set}(G/H,X) \to X^H$ be $\phi_H(f)=f(H)$. Let $\alpha :G/H' \to G/H$ be an equivariant map. To prove naturality we want to show that $$\textbf{Hom}_{G-set}(G/H,X) \overset{\phi_H}{\longrightarrow} X^H \overset{X^{\alpha}}{\longrightarrow} X^{H'}$$ and $$ \textbf{Hom}_{G-set}(G/H,X) \overset{\alpha^*}{\longrightarrow} \textbf{Hom}_{G-set}(G/H',X) \overset{\phi_{H'}}{\longrightarrow} X^{H'} $$ are the same map. Note that $X^{\alpha}(x) = \gamma x$ where $\alpha(H')=\gamma H$. Following the first diagram we get $X^{\alpha}(\phi_H(f)) = \gamma f(H) $ and following the second diagram we get $\phi_{H'}(\alpha^*(f)) = \phi_{H'}(f\alpha) = f(\alpha(H')) = f(\gamma H) = \gamma f(H)$. Thus the transformation is natural. It's also a bijection as noted at the link making it a natural isomorphism between $X^{(-)}$ and the representable functor $\textbf{Hom}_{G-set}(-,X)$.
This problem is verbatim from Peter May's book A Concise Course in Algebraic Topology.


text:
Q: Using interface for Unity RTS queueing actions I have this ICommand interface.
public interface ICommand
{
    public void PerformUnitCommand(ICommandParameters params,UnityAction callback);
}

I want to extend classes with methods as such, with varying parameters so I tried to implement it like the following:
public class MoveToDestination : ICommand
{
    public void PerformUnitCommand(ICommandParameters params, UnityAction callback) { ... }
}

public class Attack : ICommand
{
    public void PerformUnitCommand(ICommandParameters params, UnityAction callback) { ... }
}

public class Harvest : ICommand
{
    public void PerformUnitCommand(ICommandParameters params, UnityAction callback) { ... }
}

public class ICommandParameters
{
    public Vector3 Destination;
    public Target target;
    public Resource targetResource;
}

What is the best practice on solving this problem? I feel like this is not what an interface is created for and I should be using a different pattern. But I also feel like my problem should be solve by the likes of interface where in my AI script I will only call PerformUnitCommand() and the AI script will not have to know about the objects inside each class. Any thoughts is greatly appreciated !


text:
Q: extracting and saving xml results in file using SSIS I am trying to query results as XML from Oracle db using XMLElement and XMLAgg functions which gives me results in CLOB format. Now, when I try to use this query in Data Source flow task in SSIS, I get an error as unsupported data format.
Query:
select XMLElement("root",
         XMLAgg(XMLElement("person",
             XMLForest(person.first_name, person.last_name)))) AS "XMLResult"
from person

Question:
How do I use this query in SSIS (2008 R2) to avoid that error or any workaround. Further I need to write the results to a file.

A: You will need to convert the result into VARCHAR or VARCHAR2 datatype as SSIS doesn't support the XML datatype.


text:
Q: SQL Dynamic Pivot Query in SSRS 2005 In my Sql Server Reporting Services (SSRS) 2005 report, I have a query that performs a Pivot and results in a dynamic column list. I closely followed the example in http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx.
Now, the problem is my query can return different columns and I don't know the names of those columns when I'm designing my SSRS report. The query runs fine under the Data tab of the report designer, but the layout designer does not know my column names and it won't let me assign fields to be displayed.
Is there a way to do this? can I dynamically layout the dataset fields in code? can I access data columns in the data set by position rather than name?

A: You really can take advantage of reporting services to leverage a column based cross tab report.  Write the T-SQL in the db layer, then in the reporting layer drop and drop a cross tab report.  In the column grouping just add the column you need and rs is awesome and smart enough to dynamically add all columns.
Here was my original comment :):
Can you post a screen shot of what you mean? You just need to create a cross tab report in RS, it doesnt matter how many columns you have or their names. That is the advantage, you lay it in the column group and it will dynamically add all columns irregardless of names. Need more details as to what you are asking and possibly some screen shots with arrows :).
One thing to always remember - don't make your database programming to difficult - presentation should mainly and almost always be done in the front end tool, in this case reporting services.  Your database layer's code should be really simple standard T-SQL with maybe a grouping.  The client will handle the presentation issues.


text:
Q: javascript timers and css position updates I am using the following code to try and move a simple div element with id='block' down a page. but using alerts I see that my move function makes the css top value jump from 0 to 1.78957e+7px on the second call:
function init()
{
var block = $('#block');
block.css( {backgroundColor:'#ff0000',
                position:'absolute',
                top:'0px',
                left:'0px',
                height:'30px',
                width:'30px'});
block.vx = block.vy = 0.0001;
setTimeout(move(block,null),100);
}

function move(obj, t1)
{
if(t1==null)t1=new Date().getTime();
var t2 = new Date().getTime() - t1;
var rel_top = obj.vy*t2;
var rel_left = obj.vx*t2;
obj.css('top','+='+rel_top+'px');
setTimeout(move(obj,t2),100);
}

any suggestions how to make this a smooth movement please?

A: You should be using this for setTimeout:
setTimeout(function() {move(obj,t2);},100);

Otherwise you are calling the function and using its return value (undefined) as the thing to be called in 100ms.

A: You can make a recursive function call using animate which will make the transition smoother. Example:
function move()
{
    $('#block').animate({ top: '+=' + rel_top + 'px' }, function()
    {
        move();
    });
}


text:
Q: Positional Embedding in the Transformer model - does it change the word's meaning? I am reading the Transformer paper, and the Positional Embeddings make me wonder a thing:
Assume that the word "cat" is pretrained to be embedded to the word vector [2,3,1,4]. If we use the positional encoding that turns the vector into a new one, like [3,1,5,2], should not it change also the word's meaning in the word2vec matrix? Since the corpus is large, a slight change in the value can also change its meaning.

A: word2vec and Transformer treat tokens completely different.
word2vec is context-free which means bank is always some fixed vector from the word2vec matrix, in other words, the vector of bank doesn't depend on the token's position in the sentence.
On the other hand, Transformer as a input receives the tokes' embeddings and positional embeddings, to add a sense of position to the tokens. Otherwise, it relates to the text as a bag-of-words and not as a sequence.


text:
Q: Centos - my Centos 5 (hosted asterisk) always have a large CPU usage process i have a Centos 5 server which hosted asterisk 13.
server works fine last week but now top command always show me a process with large amount of CPU usage. when i kill the process a few second later another command with large CPU usage started. many times processes command is ".syslog" but have other command like "qjennjifes", "vnvebynufu" and another unknown commands like that.

A: 1) Check you have firewall and fail2ban recomended settings
2) Check you have no DoS/DDoS by "sip show channels"
3) Check your system not hacked/no broken soft on your host.


text:
Q: Sort Google Spreadsheet With Multiple Criteria Using Script I have a spreadsheet that I update on a regular basis. I also have to re-sort the spreadsheet when finished because of the changes made. I need to sort with multiple criteria like the below settings. I have searched for examples but my Google search skills have failed me.
Sort range from A1:E59
[x] Data has header rows
sort by "Priority" A > Z
then by "Open" Z > A
then by "Project" A > Z

A: Mogsdad's answer works fine if none of your cells have values automatically calculated via a formula. If you do use formulas, though, then that solution will erase all of them and replace them with static values. And even so, it is more complicated than it needs to be, as there's now a built-in method for sorting based on multiple columns. Try this instead:
function onEdit(e) {
  var priorityCol = 1;
  var openCol = 2;
  var projectCol = 3;

  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getDataRange();
  dataRange.sort([
    {column: priorityCol, ascending: true},
    {column: openCol, ascending: false},
    {column: projectCol, ascending: true}
  ]);
}

Instead of making a separate function, you can use the built-in onEdit() function, and your data will automatically sort itself when you change any of the values. The sort() function accepts an array of criteria, which it applies one after the other, in order.
Note that with this solution, the first column in your spreadsheet is column 1, whereas if you're doing direct array accesses like in Mogsdad's answer, the first column is column 0. So your numbers will be different.

A: That is a nice specification, a great place to start!
Remember that Google Apps Script is, to a large extent, JavaScript. If you extend your searching into JavaScript solutions, you'll find plenty of examples of array sorts here on SO.
As it happens, much of what you need is in Script to copy and sort form submission data. You don't need the trigger part, but the approach to sorting can be easily adapted to handle multiple columns.
The workhorse here is the comparison function-parameter, which is used by the JavaScript Array.sort() method. It works through the three columns you've indicated, with ascending or descending comparisons. The comparisons used here are OK for Strings, Numbers and Dates. It could be improved with some cleaning up, or even generalized, but it should be pretty fast as-is.
function sortMySheet() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sourceSheet.getDataRange();
  var data = dataRange.getValues();
  var headers = data.splice(0,1)[0]; // remove headers from data
  data.sort(compare);       // Sort 2d array
  data.splice(0,0,headers); // replace headers

  // Replace with sorted values
  dataRange.setValues(data);
};

// Comparison function for sorting two rows
// Returns -1 if 'a' comes before 'b',
//         +1 if 'b' before 'a',
//          0 if they match.
function compare(a,b) {
  var priorityCol = 0;  // Column containing "Priority", 0 is A
  var openCol = 1;
  var projectCol = 2;

  // First, compare "Priority" A > Z
  var result = (a[priorityCol] > b[priorityCol] ) ?
                    (a[priorityCol] < b[priorityCol] ? -1 : 0) : 1;
  if (result == 0) {
    // "Priority" matched. Then compare "Open" Z > A
    result = (b[openCol] > a[openCol] ) ?
                    (b[openCol] < a[openCol] ? -1 : 0) : 1;
  }
  if (result == 0) {
    // "Open" matched. Finally, compare "Project" A > Z
    result = (a[projectCol] > b[projectCol] ) ?
                    (a[projectCol] < b[projectCol] ? -1 : 0) : 1;
  }

  return result;
}

A: Try this using the Apps Script sort instead of the native JavaScript.  I had the same issue with sorting the header row(s) and this solved the issue.
So I think something like this should work:
function onOpen() {
  SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName("Form Responses 1").sort(2);
}

Regarding sorting by multiple columns, you can chain that sort() method, with the final sort() having the highest priority, and the first sort() the lowest. So something like this should sort by Start date, then by End date:
function onOpen() {
  SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName("Form Responses 1").sort(3).sort(2);
}

Reference link:-
https://support.google.com/docs/thread/16556745/google-spreadsheet-script-how-to-sort-a-range-of-data?hl=en

A: Not sure if this is still relevant, but you can use the sort() function to define another tab as a sorted version of the original data.
Say your original data is in a tab named Sheet1; I'm also going to act as though your Priority, Open, and Project columns are A, B, and C, respectively.
Create a new tab, and in cell A1 type:
=sort(Sheet1!A1:E59, 1, TRUE, 2, FALSE, 3, TRUE)

The first argument specifies the sheet and range to be sorted, followed by three pairs: the first of each pair specifies the column (A=1, B=2, etc.), and the second specifies ascending (TRUE) or descending (FALSE).


text:
Q: Problem while trying to update content on a jsp page using ajax in struts (when onChange event is fired) I am trying to update drop down lists when an onChange event is fired by change in selection of another drop down list.
I have 2 methods in mind:
1.) I tried using asynchronous calls using dojo, but in that case although I was able to call an action asynchronously but when the action is executed it does not update the contents of drop down lists.I guess I am missing some code which will refresh the contents of the drop downs.
Here are the codes:
The JSP page:
<%@taglib uri="/struts-tags" prefix="s" %>
<%@taglib uri="/struts-dojo-tags" prefix="sd" %>

<s:url id="scriptURL" action="getLists" />
<sd:a href="%{scriptURL}" listenTopics="getLists" formId="dayReport" showLoadingText="Working..."/>

<s:form action="viewDayReport" id="dayReport">
<s:select label="Customer " name="customer" headerKey="0" headerValue="Select" list="customerList" onchange="dojo.event.topic.publish('getLists');"/>
<s:select label="Contact "  name="contact"  headerKey="0" headerValue="Select" list="contactList"  onchange="dojo.event.topic.publish('getLists');"/>
<s:select label="Employee " name="employee" headerKey="0" headerValue="Select" list="employeeList" onchange="dojo.event.topic.publish('getLists');"/>
<s:select label="Stage "    name="stage"    headerKey="0" headerValue="Select" list="stageList"    onchange="dojo.event.topic.publish('getLists');"/>
<s:select label="Type "     name="type"     headerKey="0" headerValue="Select" list="typeList"     onchange="dojo.event.topic.publish('getLists');"/>
<sd:datetimepicker label="Date" name="date" displayFormat="dd/MM/yyyy"                             onchange="dojo.event.topic.publish('getLists');"/>
<s:submit value="View Report(s)"/>
</s:form>

The action:
The action sets all the 5 lists required in the <s:select> tags in the page.
The lists are getting generated properly, I have checked.

The struts config:
<struts>
<!-- Add your configuration elements here -->
<package name="Deutek.admin" extends="struts-default" >
    <result-types>
        <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>
    <action name="dayReportPage" class="admin.dayReportAction">
        <result type="tiles">dayReport</result>
    </action>

    //This is the action mapping which maps the action in use.(Notice that the above action is also forwarding to the same page, it is the action which first time displays the page.)

    <action name="getLists" class="admin.getLists">
        <result type="tiles">dayReport</result>
    </action>
</package>
</struts>

2.) The 2nd method I found by googling requires the following java scripting on the jsp page
function retrieveURL(url)
{
if (window.XMLHttpRequest)
{
// Non-IE browsers
            req = new XMLHttpRequest();
            req.onreadystatechange = processStateChange;
            try {
                 req.open("GET", url, true);
            } catch (e) {
                 alert(e);
            }
            req.send(null);
        } else if (window.ActiveXObject) { // IE

             req = new ActiveXObject("Microsoft.XMLHTTP");
            if (req) {
                 req.onreadystatechange = processStateChange;
                 req.open("GET", url, true);
                 req.send();
             }
        }
  }

Here the "req.open" requires "url" as a parameter. Here I dont understand what should be the URL so that the action class I have mentioned in the first method gets called.
Please tell me what code am I missing in the first method for updating the drop down lists with the new lists which were set by the action class.
Also what should be the URL in the second method.
And which method is better in your opinion.
Please help asap.
Thanks!!

A: Best way is to download struts2-showcase application from struts2 official site and extract it in your tomcat.
They have lots of example showing how various things working inside struts2 domain which includes your case like two interconnected combobox/dropdown
what you are looking can be found under ajax tab in showcase application
here is the link to download sample applications
Showcase application


text:
Q: numbers as key in ruby 1.9.x syntax How would I create a hash with numbers as keys under the new ruby syntax?  for example {abc: 123} creates a hash with the symbol abc as the key, but {123: 'abc' } throws an exception (as does {123.to_sym: 'abc'}.  The exception I see is syntax error, unexpected '}', expecting $end.  I can do  hash[123] = 'abc' or  Hash[123, 200], and could do {123 => 'abc'} under the old syntax but don't see how to create {123: 'abc'} under the new JSON style syntax.

A: You can't. The syntax is for keys which are Symbols that are also valid Ruby identifiers. 123 is a Fixnum, not a Symbol, and even if it were a Symbol, it still wouldn't be a valid Ruby identifier.

A: you can consider 123 is already a symbol because 123 is as unique as a symbol. so {123: "abc"}
is not possible.


text:
Q: Telegram Bot gets "Bad Request: message text is empty" When my Telegram bot sends sendMessage to Telegram server it gets the error message:
{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}

The problem appeared this morning, before that my bot worked a whole year without errors. GetUpdates command works well as before. I use GET HTTP method to send commads:
https://api.telegram.org/bot<MyToken>/sendMessage

with UTF-8-encoded data attached:
{"chat_id":123456789,"text":"any text"}

Has anyone encountered this?

A: Another way to send a message by emulating a form :
curl -s -X POST https://api.telegram.org/bot{apitoken}/sendMessage \
 -F chat_id='-1234567890' -F text='test message'

A: If the issue still persists, try to modify your curl request. For me adding header
'Content-Type: application/json' and -d '{"chat_id":12309832,"text":"any text"}' fixed issue

A: Well, i wrote wrapper on C language to communicate via SSL with telegram bot api. SO now I can clearly answer questions about telegram API spec.
Problem number one
First of all if we are talking about raw queries we need to remember about specifications.
By default HTTP/HTTPS post requests should consists of:

*

*<METHOD>[space]<PATH with only valid chars> <\r\n>

*<HOST valid regexed\r\n>

*<Content-type valid regexed><\r\n>

*<Content-Length with length of your POST body data><\r\n>

*<\r\n before body>

*<body>

So, i tried to send raw queries with out Content-Length and i had error same as yours. That's the first problem.
Problem number two
By default if you trying to send non valid request with sendMessage method - telegram bot api will response with error same as yours. So, yeah, that's pretty tricky error to debug...
 If you trying to send raw query, be sure that your JSON data is serialized nicely and there is no errors like shielding.
Summarizing
Request:
POST /bot<token>/sendMessage HTTP/1.1
Host: api.telegram.org:443
Connection: close
Content-Type: application/json
Content-Length: 36

{"chat_id":<integer>, "text":"test \\lol"}

Second backslash if shielding.
Code on C
sprintf(reqeustCtx.request,
            "POST /bot%s/%s HTTP/1.1\r\n"
            "Host: %s\r\n"
            "Connection: close\r\n"
            "Content-Type: application/json\r\n"
            "Content-Length: %d\r\n"
            "\r\n"
            "%s\r\n", bot_token, bot_method,
            reqeustCtx.res_addr, strlen(body), body);
    BIO_puts(bio, reqeustCtx.request);
    BIO_flush(bio);

    memset(reqeustCtx.response, '\0', BUFFSIZE);
    read_bytes = BIO_read(bio, reqeustCtx.response, BUFFSIZE);
    if (read_bytes <= 0) {
        printf("No response");
        exit(-1);
    }

    cert_free(cert_store, ssl_ctx, ca_cert_bio);
    // free memory //
    reqeustCtx.method(reqeustCtx.res_addr, reqeustCtx.request,
                      reqeustCtx.current_work_dir, reqeustCtx.current_cert);

    /* json response, need to parse */
    return reqeustCtx.response;

A: I got this error too.
I used sendMessage() method only with "low-level" Node https:
const https = require('https');

const data = JSON.stringify({
  chat_id: config.telegram.chatId,
  text: 'some ASCII text'),
});

const options = {
  hostname: 'api.telegram.org',
  port: 443,
  path: `/bot${config.telegram.botToken}/sendMessage`,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  let chunks = [];
  res.on('data', chunk => chunks.push(chunk));
  res.on('end', () => {
    const resBody = Buffer.concat(chunks).toString('utf8');
    if (res.statusCode === 200) {
      console.log(`Message sent`);
    } else {
      console.error(`${res.statusCode} ${res.statusMessage} ${res.headers['content-type']}
${resBody}`)
    }
  });
});

req.on('error', (error) => {
  reject(error)
});

req.write(data);
req.end();

And for ASCII text it was ok, however for some non-ASCII text I got:
const data = JSON.stringify({
  chat_id: config.telegram.chatId,
  text: 'Привет Мир!'),
});

Error:
400 Bad Request application/json
{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}

In my case content length was calculated with invalid length 'Content-Length': data.length (invalid for Telegram?...), so I comment out this header and now it works for UTF-8!
  headers: {
    'Content-Type': 'application/json',
    //'Content-Length': data.length
  }

A: In my case, I was using curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($fields)); to post this json via sendMessage method:
{
   "chat_id":000000000,
   "text":"Choose one of the following options: ",
   "reply_to_message_id":292,
   "reply_markup":{
      "keyboard":[
         [
             "Enable",
             "Disable"
         ]
      ]
   }
}

The problem was that when passing fields to the curl_setopt method, I was encoding the whole php array so I solved it by just encoding the reply_markup array which was a part of my json.

A: Try to put "Message" object with chat_id & text to HttpEntity in your restTemplate service, like below:
public MessageDto sendMessage(Message message) {

    return restTemeplate.exchange(
            "https://api.telegram.org/bot{token}/sendMessage",
            HttpMethod.POST,
            new HttpEntity<>(message, HttpHeaders.EMPTY),
            MessageDto.class
    ).getBody();
}


text:
Q: Switching content presenter on property, passing full data context to children? I have the following view.
<Window.Resources>
   <DataTemplate DataType="{x:Type search:SomeChildType1Vm}">
      <a:SomeParentType1 DataContext="{Binding}" />
   </DataTemplate>

   <DataTemplate DataType="{x:Type search:SomeChildType2Vm}">
      <a:SomeParentType2 DataContext="{Binding}" />
   </DataTemplate>
</Window.Resources>
<Grid>
   <Grid.RowDefinitions>
      <RowDefinition Height="*" />
   </Grid.RowDefinitions>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
   </Grid.ColumnDefinitions>

   <ContentPresenter x:Name="ContentPresenter" Content="{Binding SomeChildTypeProperty}" />
</Grid>

My datacontext for the view is a class like the following:
public class MySpecialVm
{
    public SomeChildType SomeChildTypeProperty {get;set;}
}

public class SomeChildType1 : SomeChildType
{
...
}

public class SomeChildType2 : SomeChildType
{
...
}

public class SomeChildType
{
...
}

I'd like to have the type of the SomeChildTypeProperty property control which control is displayed by the content presenter.
Is this possible? In the current format, the datacontext which gets passed to the controls is always of SomeChildType1 or SomeChildType2, which is not ideal as you can imagine. :)

A: As usual, after submitting the question I found the solution.
Using the code sample provided at https://rachel53461.wordpress.com/2011/05/28/switching-between-viewsusercontrols-using-mvvm/, I was able to produce the following.
<Window.Resources>
   <valueConverters:NullableObjectToTypeConverter
      x:Key="NullableObjectToTypeConverter" />

   <DataTemplate x:Key="SomeParentType1Template" DataType="{x:Type a:SomeParentType}">
      <a:SomeParentType1Control DataContext="{Binding}" />
   </DataTemplate>

   <DataTemplate x:Key="SomeParentType2Template" DataType="{x:Type a:SomeParentType}">
      <a:SomeParentType2Control DataContext="{Binding}" />
   </DataTemplate>

   <DataTemplate DataType="{x:Type a:SomeParentType}">
      <ContentControl Content="{Binding }">
         <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
               <Setter Property="ContentTemplate"
                       Value="{StaticResource SomeParentType1Template}" />
               <Style.Triggers>
                  <DataTrigger
                     Binding="{Binding SomeChildTypeProperty,
                     Converter={StaticResource NullableObjectToTypeConverter}}"
                     Value="{x:Type a:SomeChildType2}">
                     <Setter Property="ContentTemplate"
                             Value="{StaticResource SomeParentType2Template}" />
                  </DataTrigger>
               </Style.Triggers>
            </Style>
         </ContentControl.Style>
      </ContentControl>
   </DataTemplate>
</Window.Resources>
<Grid>
   <Grid.RowDefinitions>
      <RowDefinition Height="*" />
   </Grid.RowDefinitions>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
   </Grid.ColumnDefinitions>

   <ContentPresenter x:Name="ContentPresenter"
                     Content="{Binding}" />
</Grid>

This also required an object to type converter.
public class NullableObjectToTypeConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   {
      return value?.GetType();
   }

   public object ConvertBack(object value, Type targetType, object parameter,
      System.Globalization.CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}


text:
Q: Index of slide show being set to 1 after initial round I'm not exactly sure whats going on. On initial start-up the code runs flawlessly. However I notice that toIndex is changing from a 0 base to 1 after the initial run. Its throwing off the navigation highlighting and just making trouble in general
Here is a fiddle
And the code
Slider
// Helper function to return the first slide for the given slider
function getFirstSlide(sliderElem) {
  return sliderElem.find(".slide").eq(0);
}

// Helper function to get current slide for this slider
function getCurrentSlide(sliderElem) {
  return sliderElem.find(".currentSlide");
}

// Animate the given slider to the given slide
function animToSlide(sliderElem, slideNum) {

  // Get the current slide
  var currentSlide = getCurrentSlide(sliderElem);

  // Get the target slide
  var targetSlide;
  if(slideNum < sliderElem.data().slideCount) {
    // If the number if within the number of slides
    targetSlide = sliderElem.find(".slide").eq(slideNum);
  } else {
    // If the number is not within the number of slides, wrap to the first
    targetSlide = getFirstSlide(sliderElem);
  }

  // Position the target slide (currently invisible) above the current slide
  targetSlide.css({"z-index": 500});

  // Position the current slide under the target slide
  currentSlide.css({"z-index": 100});

  // Add currentSlide class to the target slide. Triggers CSS3 transition to start fading it in
  targetSlide.addClass("currentSlide");

  if(sliderElem.data().onSlideChange !== undefined) {
      sliderElem.data().onSlideChange(currentSlide.index(), slideNum);
  }

  // Wait for the animation duration before removing the currentSlide class from the current slide
  // Ensures that target slide in fully visible before the current slide fades away
  setTimeout(function() {
    currentSlide.removeClass("currentSlide");

  }, sliderElem.data().animDuration);
}

// Start a timer for the slider with the given duration, and save a reference to it
function startSliderTimer(sliderElem, slideDuration) {
  if(sliderElem.data().autoSlide){

  // Save the timer to the slider's data in case we need to cancel it later
  sliderElem.data({
    slideTimer: setTimeout(function() {

      sliderTickEvent(sliderElem);

    }, slideDuration)
  });
  }
}

// Used to manually set the current slide of the given slider to the given slide
function setSlide(sliderElem, slideNum) {

  // Cancel if an attempt is made to switch to the current slide
  if(slideNum == getCurrentSlide(sliderElem).index()) {
    return;
  }

  // Get the current timer for this slider
  var slideTimer = sliderElem.data().slideTimer;

  // Stop it if it exists
  if(slideTimer !== undefined) {
    clearTimeout(slideTimer);
  }

  // Animate to the given slide
  animToSlide(sliderElem, slideNum);

  // Set a new timer
  startSliderTimer(sliderElem, sliderElem.data().slideDuration);
}

// This is called on a timer.
// Calls animToSlide to the next slide
function sliderTickEvent(sliderElem) {
  // Get current slide number by looking at DOM
  var currentSlide = getCurrentSlide(sliderElem).index();

  // Animate to the next slide
  animToSlide(sliderElem, currentSlide + 1);

  // Start a timer.
  startSliderTimer(sliderElem, sliderElem.data().slideDuration);
}

// Given an object of options, initialize a new slider
function initSlider(sliderOptions) {

  // Get the slider element
  var sliderElem = sliderOptions.sliderElem;

  // Take the slider container and add our generic class
  sliderElem.addClass("slider");

  // Take the slides and add our generic class
 sliderElem.find(sliderOptions.slideSelector).addClass("slide");

  // Apply slider sizing
  sliderElem.css({
    width: sliderOptions.sliderWidth,
    height: sliderOptions.sliderHeight
  });

  // Apply transition effect to slide
  sliderElem.find(".slide").css({
    transition: "opacity " + sliderOptions.animDuration + "s " + sliderOptions.animTimingFunc
  });

  // Count the number of slides and save it in the slider options
  sliderOptions.slideCount = sliderElem.find(".slide").length;

  // Store the slider options on the slider element itself
  sliderElem.data(sliderOptions);

  //Start a timer for this slider
  startSliderTimer(sliderElem, sliderOptions.slideDuration);

  //Add dot nav
  if(sliderElem.data().dotNav){
    innerDiv = '';
    sliderElem.find('.slide').each(function() {
      innerDiv += '
⋅
';
    });
    slideNav = '
' + innerDiv + '
';
    sliderElem.append(slideNav);
    sliderElem.find('.slideNavDot').eq(0).addClass('dotSelected');
  }
}

$(document).ready(function() {

    var defaultSliderOptions = {
        //jQuery object for the slider container
        sliderElem: null,

        //jQuery selector for a slide
        slideSelector: null,

        //Slide duration in milliseconds
        slideDuration: 7000,

        // Animation duration in seconds
        animDuration: .7,

        // ease, ease-in, ease-out, ease-in-out, etc
        animTimingFunc: 'ease',

        sliderWidth: '100%',
        sliderHeight: '100%',
        autoSlide: true,

        onSlideChange: undefined
    };
    initSlider($.extend({}, defaultSliderOptions, {
        sliderElem: $("#campus-slider"),
        slideSelector: ".campusSlide",
        dotNav: true,
        onSlideChange: function(fromIndex, toIndex) {
            $('#campus-slider').find(".slideNavDot").addClass('campusDot');
            $('.campusDot').removeClass("dotSelected").eq(toIndex).addClass("dotSelected");
            $('.slideCover').css('background-image', 'none');
            console.log(toIndex);
        }
    }));

    $('#campus-slider').find('.slideNavDot').click(function() {
        setSlide($("#campus-slider"), $(this).index());
        $('#campus-slider').find('.slideNavDot').removeClass('dotSelected');
        $(this).addClass('dotSelected');
    });

});

A: It looks like the only issue is that you don't have a reset condition to highlight the first dot. The JQuery method .eq() is zero-based (see here) and your toIndex will never be zero. Since you're always highlighting the next dot (fromIndex + 1) and fromIndex is never less than zero, it makes sense that you never highlight the first dot in the cycle.
Try adding this in your onSlideChange event:
onSlideChange: function(fromIndex, toIndex) {
    $('#campus-slider').find(".slideNavDot").addClass('campusDot');

    // if we exceed the lengths of the dots
    var $dots = $('.campusDot');
    if($dots.length === toIndex) {
        // reset to zero index
        toIndex = 0;
    }

    $('.campusDot').removeClass("dotSelected").eq(toIndex).addClass("dotSelected");
    $('.slideCover').css('background-image', 'none');
    console.log(toIndex);
}

Fiddle


text:
Q: Why would the Facebook auth callback from omniauth-facebook not be returning the email and UID? Certain users in our application reported not being able to log in via their Facebook account. I looked into it and was able to repro an issue where the callback hash doesn't contain the uid or the email. Here's an example of the hash:
#<OmniAuth::AuthHash credentials=#<OmniAuth::AuthHash expires=true expires_at=1409288689 token="CAALQVOrveN4BAHwlBhXvuefS1m7KIq0mWZCGrXslpbrsp4SJXMZBTj2ZC7T8YJHMA8QCywws91I4ZCZCj0oUZAAzkJuwYuHvsRUUEZBnUSnAxpbSuOJZCuKXpWZBZAeHkjcIR0IQCorkFTvV4BGu9UcN8hnEeaWST5DTjOR5lkRvVTsijlPSokvwgD"> extra=#<OmniAuth::AuthHash raw_info="\x1F\x8B\b\x00\x00\x00\x00\x00\x00\x03\xB5Vmo\xDB6\x10\xFE+\x84>\xEC\xCB\xEC\x84\xAF\x92\x98oi\x82\x0E\xED\xD6\xB5H2\x04\xC5\\\x04\x8Ct\x8E8\xCB\xA4F\xD11\x9C\xA2\xFF}G%\xA9\x99\x97\r\x18\xB0\x01\xB6\x00\x91w\xC7\xBB\xE7y\xEE\xA8\xAF\x85m\x8B\xA3BiJ\xA9\x94\xBC\x98\x15\xB06\xB6\xC7\xA5\xA6\x19\x9Bnm\xE3\xDDb\x83[\xF4&-\x1F4~\x8D&Ks\xEB\x83\x8Dpeb\xD7C\x84\xB18\xFA\xFD\xEB} F\x19\xA5\x82J!X]q\x86\xC6\xCE\xAC\x017\xCE\xCC\x8E\x1C\xF7=\xB8\xE2\xDB\xEC\xC1\xB6\xD2\x1A\x7FLh\x9D\xCE}\xB0;\xDD\xEE\x8C\x03riZ\xD8[\x96\xB2*\xA9\xD6RK\x9AE\xF47\x10\xC8[h!@\xC8l\xB9\xAE\x14\xC6dZ\xECm?\xD8\xA63\xD0\x93\xF7>\xB4&K\x81\xD1\x92\xD6T2-\xB9\xD0e\x96\xEE\xB1\t\xDE\x913\xDF\xE2\x19cn\xAFJ\xC6j)\x98\xCCR\xF6\xCE\xF4-9\r\xF66%\xF2%\x03(\x82Yg\xE8HEkQ+\xC4:\xAB\xF8\x83\xED\xB7f\xB3\x02 o\x02l\x9F\x1E\xA7YM\x95\xE45+_\xB5\xDF4\xAB\xCC\xBAbe\xC54U\xB4\xCA\xA2\xFF\x14\x00\x1Cy\x83\xE8\x7F2\xCDj\x8A\x9E\x12\xB4a\x8CW\x0F&']\xB0#z\xDC\x80C,qamz\xC0\xF7\xCE\xAF!\xFA\xAD+\x8E\xBEW/\xAARh\xCE\xB5V\x9Cg\b\x1C\x0F\x03\xEA\xC0\xBB\x19\xB9\xB4c\xE3\xDDh\x13\xC6\x85u\xE3`\x83\x896\x01t5\x80G\xAB\\*\x92I\xCA\xEB\x92\xD7\xB5\x92\xD5>\xDA{\xDF!\xF40\xDA\x9B\f\x89J\xD6\xA5\xD6TsZ\x89:\xAB\xEF3t\x9B\xD6\x90\x9FM\xBC\x9B*\xEB\xCD\xBE\xB0\xF3{\x01\xA3qo\xDD\n\x17\xBA\x18\x87\xF1hq\xB88\xDCn\xB7\aK\xD3\xC0\xB5\xF7\xAB\xA4\xEA\xC5\xE1w\xBD's\xDFLY\xEF+g\\\n\x84\xB6\xAE*\xA6\x9E\xC8\x15\xC8'\xD4\xDF\xB3\xC2\x93\x7F*\xB5\x00w\xF5\xDB\xF9\xDEzB\x9A\xEC\xD3\x1A|o\xA3E\xDB\xB4\x87\xDE\x10n\xF1\xDC\xDB\x04~\x80\xDE\xDEL)\xDC{E\x8B\xBA\x9D\x15\xE3\xE0C|\xD2o5GV*\x9D\x9E*\x13\xF0\xB9_\xC6k\xD3\xF7\xB9v\xB5(\xEB\xAA\xE6\x92sQe\xEC\x9Dm\x9C\xB3.\x03[2\x81\x12\x15Z\xC9\x1A\x9FY\xCB]\x00Z\x8E\x04;\xE3\xED\x03v\x13\xE6\x7Fn\xFC4\x04\x8AE\xF1\xD9\x90\x95\xF3[\xB2\xEDL$\xB1\x83\x1D\x19\xCD\xEE\xE0\xE0\x80\x90w\xCB\xF4N\xC6\xCE\x03Y\xDA8\xCEH\f;bc\x8Af\\\x8B\x9B\xC8\x111\xD7~\x13quQ\x90995\x0E\xDB\xCFoFr\n\xC6\x91\xF3\xCE\xF4\xAB\x0E_Q\xA4\xB3\"\xDA5\xDCy\x87i\xCD\xD5\xAC\xD8\f\xAD\x89\xD0^\xA5UL\x84S&\xE7\xB4\x9C\xB3\xEA\x82\xF3#Q\x1EQ\xF5#\x96\x94JI\xEE\x0F\xE5\xE4\x94c\xEB\xDA\xA5\x05,?\x86\r\xCC\x8A\xAD\x0F\xAB\tfX\x0F\xBD\xDF\xA5\xBEx@\x87\xEB\x922\xC1q\xC8\x958\a\xB2!s\t\x1F\xBC\x8B\xE6&\r\xAEW$DK\xC6+\xEC\xCDJq-\xD5\xDE\xEDWlP\xD3=S\xD0\xE0G\xFB\xC4\x1D+\xE2\x8C\xE3p\xD3eU\xD6\x99\xFB\xC9\xC5G\xF2\x039\xF1\x88\xD7\xD2o\xA6\x0EF\xFF1\x9A\x10\xAF\x12&\xF7\xBE\"\xA1A\xD9\xC4\xF1\x8B\x8A\x98\xAA\xB0\xAB1\xBB\xAA\x948\x103u\xA3\x04\xA3\xE9q\xC8\x86h{{w\x1F\xFBen\x8A\n\x81\x7F\x96\xCASY'\x9F\xF8\xF9\xDB\x7F\xCCI<\xE6\xD4\xC2\xD8\x04;\xDC\x87-\xDE\xA1\xCB\x90\xA6\x91\x8Bd\v\xD7\xA4\x85[\xE8\xFD\x80\xE3>)%\xA1\xB4\xE9\xA3q\xF1\xA0H\xF7\xD5\xB3j\x14+\xB1'\xB4\xAA\x85\xAEe\xCE\xCF\x93\xEE#\xBF\xFCr\xF2:O\xFF\xAE\xD5_\x80\xC1\x18\x82\xC0q\xCCk\xA5\xA8\xCA\xFC?n\xDD\xDF\xE2\xC0\xBEs\xE3\xDA\xC7\x9D\xA4\xD7\xF9$\xD9\x17%J,N\xF2twUx\xD5\xD6Y\x83b\x87\x9D\x04\xBCt \xEC\xFE\xBB\xEC\xF8\xEB,!\xBB\x93\x17\xF1\xCB\x84L\x03\xD3F\x02vF\fY\x9B\xB0\x82\x88s\x05\xF9Z\x0F\xC6\xEDP\x9E\x81\x8Cx\xB7\xF4\xE4z\x83\xE8\xC18\xC2\x88m\x8F\x83b\x1C\xA0\xB1&\tl$\xD6M\x94'\xA2\x87`Q\x00m\xBA\t\xDCD\xF5\x1E\x9C\xD4\x0Es6%\xF6\n>B\xE2\xB7\x8C\x16\xA9\xD52\xFE\xF79\xFE/\xC4s\x81\x13\x13\x8F,\xCBJ(\xA9\x9FA\xBB8\xBC\x84\xEB\xD3G\x1DO\x01\x82\xFF\x03\x9A|\x98\xF3\n\xBFBx\xC5\x90\x1F\xAADb\xFE)\xE0\xC7\xE4\x12\xBF_>\x05D.\xCD\xD2\xF54M\x87\x84\xCC\x9E\xFE5\x9C\xC1\x12-:\\\xDD\xDA\xD8\xED\xA3+Q*IE\xFE\tu\x81W\xBC\x19\xC9\e\x9B\xE2\xE0(O\xC3\xFC\x19\xFFT?v\xE9\x97o\x7F\x01\x16\a+3-\n\x00\x00"> info=#<OmniAuth::AuthHash::InfoHash image="http://graph.facebook.com//picture"> provider="facebook" uid=nil>

Notice at the end, the info hash doesn't contain the email field or a valid image URL. This response is for my account (I am an admin for the FB app) and I am getting this in development and production. Tested on a handful of other accounts though and it seems to be working for most.

A: I cant comment because of low rep however, could it be down to permissions they have set on their facebook accounts. Here is a a section taken from their docs https://developers.facebook.com/docs/facebook-login/permissions/v2.0


text:
Q: Img displayed in binary code with correct header on browser I build a class of  imgResize:
class imgResize
{
   public static function resizeAndOutput($img) {

    $orginal_img = $img;
    $width = 591;
    $height = 332;
    $new_width = 161;
    $new_height = 91;

    $edit_img = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($orginal_img);
    imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    header('Content-Type: image/jpeg');

    imagejpeg($edit_img);
}

}
and in html I try to get this on the fly img displayed:
<img class="img_small" src="<?php imgResize::resizeAndOutput($img)">

just getting binary datas like this:
�����JFIF���������>CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality ���C�           $.'

How can i solve my problem?

A: you have to encode your image in a data uri (and embedding the base64 encoded data as a string in your html) and removing that header() line in php,
or create a link to that image, for example http://example.com/?myimage=id and outputting the image as you are doing (as in giving correct headers and echoing the resulting image)
tell me if you need more info or this gives enough insights.

A: If you output it directly into a src element, it will of course just be binary garbage inside HTML. That's not how  elements work. An  element's src needs to have a URL pointing to the image. This can be either a URL like img/foo.jpg, or app/some_script_that_outputs_an_image.php, or a Data URI. But not simply binary data. The script that outputs the image would work in this second case, as target of a app/some_script_that_outputs_an_image.php link.

A: You actually do it right but in the last part you have a problem. You have to save the image and then return the url of the image to the img element.. Try this code:
class imgResize
{
   public static function resizeAndOutput($img) {

    $orginal_img = $img;
    $width = 591;
    $height = 332;
    $new_width = 161;
    $new_height = 91;

    $edit_img = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($orginal_img);
    imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    header('Content-Type: image/jpeg');

    //Now we have the image lets create a random filename
    //Modify this to your needs
    $filename = "images/IMG_" . mt_rand(1000,9999) . ".jpg";
    //Random sometimes sucks.. Lets see if we already got a file with that name
    //And if exists, loop until we get a unique one
    while(file_exists($filename)) {
        $filename = "images/IMG_" . mt_rand(1000,9999) . ".jpg";
    }
    //Now let's save the file
    imagejpeg($edit_img, $filename);
    //And finally return the file url
    return $filename;
}
}

If you don't want to save it, you should output it directly to the browser. You don't need any img tags. That's because when using imagejpeg it's like you have directly opened an image file in the browser. (I don't know if I was clear or not. I'm just trying to describe what it really is)
So the php file will be same and you don't need any html. Just call the function. it will do what it is needed:
imgResize::resizeAndOutput($img);

A: class imgResize

{
   public static function resizeAndOutput($img) {
$orginal_img = $img;
$width = 591;
$height = 332;
$new_width = 161;
$new_height = 91;

$edit_img = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($orginal_img);
imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
ob_start ();
imagejpeg($edit_img);
$image_data = ob_get_contents ();
ob_end_clean ();
return base64_encode($image_data);

}
HTML
<img class="img_small" src="data:image/jpeg;base64,<?php echo imgResize::resizeAndOutput($img)">


text:
Q: I need the compliment of text file containing "ATGC" I have a text file containing string formed by only four type of characters A,T,G,C
 for example-
TGTGGCCAAGAAAACAGGAAAAGAGGGCGGACCGAAAATCATGGTTGCCGGACACCTGGA
CGAAGTAGGATTCATGATCACAAGCATTGATGACAAAGGCTTCCTCCGCTTCCAGACGGT
CGGTGGCTGGTGGTCACAGGTTATGCTTGCCCAGCGTGTCACCATTGTAACTAGCAAAGG

now I need the compliment of above text file using PHP
and compliment of
A is T,
T is A,
G is C,
C is G.

MY CODE IS
$str = TGTGGCCAA;

$str =str_replace("A","T",$str);
$str =str_replace("T","A",$str);
$str =str_replace("G","C",$str);
$str =str_replace("C","G",$str);

echo"$str";

A: Use strtr function, see the code below (I've just make yout input string shorter):
<?php

$str = 'TGTGGCCAAGAAAACAGGAAAAGAGGGCGGACCG';
echo strtr($str, array('A' => 'T', 'T' => 'A', 'G' => 'C', 'C' => 'G'));
// out: ACACCGGTTCTTTTGTCCTTTTCTCCCGCCTGGC

?>


text:
Q: Find ranges from a series of numbers in SQL/Oracle I have a table containing a series of numbers 1,2,3,4,5,11,12,13,14,15,101,102,103,104,105,510,511,512,513,515,516,517. I want an SQL Query, Procedure or Function so that I can get the ranges in the following formats.
From-To:
1-5
11-15
101-105
510-517

OR
1-5, 11-15, 101-105, 510-517

A: You could do it using ROW_NUMBER analytic function. See Find range of consecutive values in a sequence of numbers or dates.
For example,
Range
SQL> with data(num) as(
  2      select  1 from dual union
  3      select  2 from dual union
  4      select  3 from dual union
  5      select  5 from dual union
  6      select  6 from dual union
  7      select  7 from dual union
  8      select 10 from dual union
  9      select 11 from dual union
 10      select 12 from dual union
 11      select 20 from dual
 12  )
 13  select min(num)||'-'|| max(num) as "range"
 14  from (select num,
 15           num-Row_Number() over(order by num)
 16           as rn
 17           from data)
 18  group by rn
 19  order by min(num);

range
-------------------------------------------------
1-3
5-7
10-12
20-20

SQL>

List
SQL> with data(num) as(
  2      select  1 from dual union
  3      select  2 from dual union
  4      select  3 from dual union
  5      select  5 from dual union
  6      select  6 from dual union
  7      select  7 from dual union
  8      select 10 from dual union
  9      select 11 from dual union
 10      select 12 from dual union
 11      select 20 from dual
 12  )
 13  SELECT listagg(range, ',') WITHIN GROUP(
 14  ORDER BY min_num) AS "list"
 15  FROM
 16    (SELECT MIN(num) min_num,
 17      MIN(num)
 18      ||'-'
 19      || MAX(num) range
 20    FROM
 21      (SELECT num, num-Row_Number() over(order by num) AS rn FROM DATA
 22      )
 23    GROUP BY rn
 24    );

list
-------------------------------------------------------------------------
1-3,5-7,10-12,20-20

SQL>

Update OP wants a solution in PL/SQL to store the list in a PL/SQL variable.
Setup
SQL> CREATE TABLE t AS
  2  SELECT *
  3  FROM
  4    ( WITH data(num) AS
  5    ( SELECT 1 FROM dual
  6    UNION
  7    SELECT 2 FROM dual
  8    UNION
  9    SELECT 3 FROM dual
 10    UNION
 11    SELECT 5 FROM dual
 12    UNION
 13    SELECT 6 FROM dual
 14    UNION
 15    SELECT 7 FROM dual
 16    UNION
 17    SELECT 10 FROM dual
 18    UNION
 19    SELECT 11 FROM dual
 20    UNION
 21    SELECT 12 FROM dual
 22    UNION
 23    SELECT 20 FROM dual
 24    )
 25  SELECT * FROM DATA);

Table created.

PL/SQL block
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  2    v_list VARCHAR2(100);
  3  BEGIN
  4    SELECT listagg(RANGE, ',') WITHIN GROUP(
  5    ORDER BY min_num)
  6    INTO v_list
  7    FROM
  8      (SELECT MIN(num) min_num,
  9        MIN(num)
 10        ||'-'
 11        || MAX(num) range
 12      FROM
 13        (SELECT num, num-Row_Number() over(order by num) AS rn FROM t
 14        )
 15      GROUP BY rn
 16      );
 17    dbms_output.put_line(v_list);
 18  END;
 19  /
1-3,5-7,10-12,20-20

PL/SQL procedure successfully completed.

SQL>

A: The common solution exploits the fact that those values should be sequential:
select min(serialnum), max(serialnum), count(*)
from
 (
   select
      serialnum,
      -- this returns a meaningless value, but the same meaningless value for sequential numbers
      serialnum - row_number() over (order by serialnum) as dummy
   from tab
 ) dt
group by dummy


text:
Q: Prepared SQL LIKE statement not returning all results I have a function to search my ingredient DB (error reporting removed for clarity):
    $servername = "localhost";
    $username = "root";
    $password = "*****";
    $dbname = "addb_db";

    $query = "%" . $_POST["query"] ."%";

    $conn = new mysqli($servername, $username, $password, $dbname);

    $sql = "SELECT id, name FROM addb_ingredients WHERE name LIKE ? or id like ?";
    $stmt = $conn -> prepare($sql)
    $stmt->bind_param('ss', $query,$query)
    $stmt->execute()
    $stmt->bind_result($id,$name)
    while ($stmt->fetch()) {
        $ing_array[] = array($id,$name);
    }
    $response_array["status"] = "success";
    $response_array["data"] = $ing_array;

    echo json_encode($response_array);

    $stmt->close();
    $conn->close();

This only returns partial results for particular queries, e.g. for "bi", these are the results returned:

*

*Bison Grass Flavored Vodka

*Bitter

*Bitter Lemon

*Bitters

*Celery Bitters

*Chilled hibiscus tea

*Chocolate Bitters

*Orange Bitters

*Peach Bitters

*Peychaud's bitters

*Wasabi Paste

Running this query on phpMyAdmin returns the same, as it should.
However, when entering "bit", the results from the php above are:

*

*Bitter Lemon

*Bitters

*Celery Bitters

*Chocolate Bitters

*Orange Bitters

*Peach Bitters

*Peychaud's bitters

Whereas the results should be:

The 'bitter' result is excluded and I can't work out why.

A: I'm not particularly strong with PHP, but I've noticed that 'Bitter' would have been the first result if using '%bit%' as a parameter. Likewise, 'Absolut Hibiskus' should be the first result when using '%bi%' as a parameter.
My guess is that the first result is consumed within this block of code without actually being assigned anywhere within $ing_array:
$stmt->bind_result($id,$name)
while ($stmt->fetch()) {
    $ing_array[] = array($id,$name);
}

A: Quite indicative, there are no screenshots for the actual output provided. Means the OP is judging their prepared statement output by distant indirect consequences. Like some processing on the client side.
There are no errors neither in prepared statements nor in LIKE statement responsible for such a behavior. 100% of reported errors of the same kind were caused by the userland code.


text:
Q: How to handle this function? I wanted to wrote a function where street fighters attacking them alternately. Each attack pulls some hearts of. When one of the fighters has 0 hearts, the fight is over. But I don't know how to do this process again and again. This is how my code looks right now:
public struct StreetFighter {
    var name: String
    var power: Int
    var defence: Int
    var hearts: Int
    func Attack() {
        print("\(name) is going into the offence...")
    }
    func Blocking() {
        print("\(name) is blocking the attack")
    }
}
var connorMcGregor = StreetFighter(name: "Connor McGregor", power: 8, defence: 7, hearts: 100)
var mikeTyson = StreetFighter(name: "Connor McGregor", power: 9, defence: 6, hearts: 100)
var alisterOverreem = StreetFighter(name: "Alister Overreem", power: 7, defence: 10, hearts: 100)
var khabib = StreetFighter(name: "Khabib", power: 9, defence: 8, hearts: 100)

struct Fight {
    var location: String
    mutating func Round1(firstFighter: StreetFighter,secondFighter: StreetFighter) -> Int {
        firstFighter.Attack()
        if firstFighter.power < secondFighter.defence  {
            secondFighter.Blocking()
            secondFighter.Attack()
        } else {
        secondFighter.hearts - firstFighter.power
            }

            if secondFighter.power < firstFighter.defence  {
                firstFighter.Blocking()
            } else {
        firstFighter.hearts - secondFighter.power
            }
        if firstFighter.hearts == 0 || secondFighter.hearts == 0 {
        print("The fight is over!")

        }
        return firstFighter.hearts
        return secondFighter.hearts
    }
}

var mma = Fight(location: "New York")
mma.Round1(firstFighter: connorMcGregor, secondFighter: khabib)

The problem is that the process stops after the first round. I tried it with for-in or repeat-while loops but without any success.
Can anybody helps me?

A: First, you may try to move some functions to the StreetFighter itself:
public struct StreetFighter {
    let name: String
    let power: Int
    let defence: Int
    var hearts = 100 // you can provide a default value

    var isAlive: Bool {
        hearts > 0
    }

    func attack() {
        print("\(name) is going into the offence...")
    }

    mutating func defend(attackingPower: Int) {
        if power > defence {
            hurt(damage: attackingPower)
        } else {
            block()
        }
    }

    private func block() {
        print("\(name) is blocking the attack")
    }

    private mutating func hurt(damage: Int) {
        print("\(name) is hurt")
        hearts -= damage
    }
}

Then, add a function in the Fight struct with a while loop (you can limit the number of rounds there as well):
struct Fight {
    let location: String
    var fighter1: StreetFighter
    var fighter2: StreetFighter

    mutating func start() {
        var roundNumber = 0
        while !isFinished && roundNumber < 12 {
            roundNumber += 1
            round()
            print("Round \(roundNumber): \(fighter1.name) - \(fighter1.hearts), \(fighter2.name) - \(fighter2.hearts)")
        }

        print("The fight is over!")
    }

    private mutating func round() {
        fighter1.attack()
        fighter2.defend(attackingPower: fighter1.power)
        fighter2.attack()
        fighter1.defend(attackingPower: fighter2.power)
    }

    private var isFinished: Bool {
        !fighter1.isAlive || !fighter2.isAlive
    }
}

Now you can start your fight:
let connorMcGregor = StreetFighter(name: "Connor McGregor", power: 8, defence: 7, hearts: 100)
let mikeTyson = StreetFighter(name: "Connor McGregor", power: 9, defence: 6, hearts: 100)
let alisterOverreem = StreetFighter(name: "Alister Overreem", power: 7, defence: 10, hearts: 100)
let khabib = StreetFighter(name: "Khabib", power: 9, defence: 8) // you can use the default `hearts` count

var mma = Fight(location: "New York", fighter1: connorMcGregor, fighter2: khabib)
mma.start()

Depending on your goal you may want to extract some parts of Fight outside. For example the start function can return a result (who won) and you can operate on it then.