text:
#include <vector>
#include <vnl/vnl_vector.h>
#include <vnl/vnl_real_npolynomial.h>
#include <vcl_compiler.h>

//: Solves for roots of system of real polynomials
//  Calculates all the roots of a system of N polynomials in N variables
//  through continuation.
//  Adapted from the  PARALLEL CONTINUATION algorithm, written by Darrell
//  Stam, 1991, and further improved by  Kriegman and Ponce, 1992.

class vnl_rnpoly_solve
{
  // Data Members--------------------------------------------------------------
  std::vector<vnl_real_npolynomial*> ps_;   // the input
  std::vector<vnl_vector<double>*> r_; // the output (real part)
  std::vector<vnl_vector<double>*> i_; // the output (imaginary part)

 public:

  // Constructor---------------------------------------------------------------

  //: The constructor already does all the calculations
  inline vnl_rnpoly_solve(std::vector<vnl_real_npolynomial*> const& ps)
    : ps_(ps) { compute(); }

  // Destructor----------------------------------------------------------------

 ~vnl_rnpoly_solve();

  // Operations----------------------------------------------------------------

  //: Array of real parts of roots
  inline std::vector<vnl_vector<double>*> real() { return r_; }

  //: Array of imaginary parts of roots
  inline std::vector<vnl_vector<double>*> imag() { return i_; }

  //: Return real roots only.
  //  Roots are real if the absolute value of their imaginary part is less than
  //  the optional argument tol, which defaults to 1e-12 [untested]
  std::vector<vnl_vector<double>*> realroots(double tol = 1e-12);

  // Computations--------------------------------------------------------------

 private:
  //: Compute roots using continuation algorithm.
  bool compute();

  void Read_Input(std::vector<unsigned int>& ideg,
                  std::vector<unsigned int>& terms,
                  std::vector<int>& polyn,
                  std::vector<double>& coeff);
};

#endif // vnl_rnpoly_solve_h_


text:
package Recursion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TraingleApp {
    static int theNumber;
    //--------------------------------------------------------------------------
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        System.out.print("Enter a number : ");
        theNumber=getInt();
        int theAnswer=traingle(theNumber);
        System.out.println("Traingle = "+theAnswer);
    }
    //--------------------------------------------------------------------------
    public static int traingle(int n){
        if(n==1)
            return 1;
        else
            return (n+traingle(n-1));
    }
    //--------------------------------------------------------------------------
    public static String getString() throws IOException{
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        String s=br.readLine();
        return s;
    }
    //--------------------------------------------------------------------------
    public static int getInt() throws IOException{
        String s =getString();
        return Integer.parseInt(s);
    }
    //--------------------------------------------------------------------------
}
/* OUYPUT
Enter a number : 10
Traingle = 55
*/

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: 10 - Slow
---


text:
package collide.shared.collect;

import java.util.Iterator;

import elemental.util.ArrayOf;

public class ArrayOfIterator<T> implements Iterator<T> {

  private final ArrayOf<T> array;
  private int pos;

  public ArrayOfIterator(ArrayOf<T> array) {
    this.array = array;
  }

  @Override
  public boolean hasNext() {
    return pos < array.length();
  }

  @Override
  public T next() {
    assert pos >= 0;
    assert pos < array.length();
    return array.get(pos++);
  }

  @Override
  public void remove() {
    assert pos > 0;
    assert pos <= array.length();
    array.removeByIndex(--pos);
  }

}


text:
package rel_test

import (
	"os"
	"testing"

	"github.com/araddon/qlbridge/testutil"
)

func TestMain(m *testing.M) {
	testutil.Setup() // will call flag.Parse()

	// Now run the actual Tests
	os.Exit(m.Run())
}
func TestSuite(t *testing.T) {
	testutil.RunTestSuite(t)
}


text:
module Aws::NimbleStudio
  module Plugins
    class Endpoints < Seahorse::Client::Plugin
      option(
        :endpoint_provider,
        doc_type: 'Aws::NimbleStudio::EndpointProvider',
        docstring: 'The endpoint provider used to resolve endpoints. Any '\
                   'object that responds to `#resolve_endpoint(parameters)` '\
                   'where `parameters` is a Struct similar to '\
                   '`Aws::NimbleStudio::EndpointParameters`'
      ) do |cfg|
        Aws::NimbleStudio::EndpointProvider.new
      end

      # @api private
      class Handler < Seahorse::Client::Handler
        def call(context)
          # If endpoint was discovered, do not resolve or apply the endpoint.
          unless context[:discovered_endpoint]
            params = parameters_for_operation(context)
            endpoint = context.config.endpoint_provider.resolve_endpoint(params)

            context.http_request.endpoint = endpoint.url
            apply_endpoint_headers(context, endpoint.headers)
          end

          context[:endpoint_params] = params
          context[:auth_scheme] =
            Aws::Endpoints.resolve_auth_scheme(context, endpoint)

          @handler.call(context)
        end

        private

        def apply_endpoint_headers(context, headers)
          headers.each do |key, values|
            value = values
              .compact
              .map { |s| Seahorse::Util.escape_header_list_string(s.to_s) }
              .join(',')

            context.http_request.headers[key] = value
          end
        end

        def parameters_for_operation(context)
          case context.operation_name
          when :accept_eulas
            Aws::NimbleStudio::Endpoints::AcceptEulas.build(context)
          when :create_launch_profile
            Aws::NimbleStudio::Endpoints::CreateLaunchProfile.build(context)
          when :create_streaming_image
            Aws::NimbleStudio::Endpoints::CreateStreamingImage.build(context)
          when :create_streaming_session
            Aws::NimbleStudio::Endpoints::CreateStreamingSession.build(context)
          when :create_streaming_session_stream
            Aws::NimbleStudio::Endpoints::CreateStreamingSessionStream.build(context)
          when :create_studio
            Aws::NimbleStudio::Endpoints::CreateStudio.build(context)
          when :create_studio_component
            Aws::NimbleStudio::Endpoints::CreateStudioComponent.build(context)
          when :delete_launch_profile
            Aws::NimbleStudio::Endpoints::DeleteLaunchProfile.build(context)
          when :delete_launch_profile_member
            Aws::NimbleStudio::Endpoints::DeleteLaunchProfileMember.build(context)
          when :delete_streaming_image
            Aws::NimbleStudio::Endpoints::DeleteStreamingImage.build(context)
          when :delete_streaming_session
            Aws::NimbleStudio::Endpoints::DeleteStreamingSession.build(context)
          when :delete_studio
            Aws::NimbleStudio::Endpoints::DeleteStudio.build(context)
          when :delete_studio_component
            Aws::NimbleStudio::Endpoints::DeleteStudioComponent.build(context)
          when :delete_studio_member
            Aws::NimbleStudio::Endpoints::DeleteStudioMember.build(context)
          when :get_eula
            Aws::NimbleStudio::Endpoints::GetEula.build(context)
          when :get_launch_profile
            Aws::NimbleStudio::Endpoints::GetLaunchProfile.build(context)
          when :get_launch_profile_details
            Aws::NimbleStudio::Endpoints::GetLaunchProfileDetails.build(context)
          when :get_launch_profile_initialization
            Aws::NimbleStudio::Endpoints::GetLaunchProfileInitialization.build(context)
          when :get_launch_profile_member
            Aws::NimbleStudio::Endpoints::GetLaunchProfileMember.build(context)
          when :get_streaming_image
            Aws::NimbleStudio::Endpoints::GetStreamingImage.build(context)
          when :get_streaming_session
            Aws::NimbleStudio::Endpoints::GetStreamingSession.build(context)
          when :get_streaming_session_stream
            Aws::NimbleStudio::Endpoints::GetStreamingSessionStream.build(context)
          when :get_studio
            Aws::NimbleStudio::Endpoints::GetStudio.build(context)
          when :get_studio_component
            Aws::NimbleStudio::Endpoints::GetStudioComponent.build(context)
          when :get_studio_member
            Aws::NimbleStudio::Endpoints::GetStudioMember.build(context)
          when :list_eula_acceptances
            Aws::NimbleStudio::Endpoints::ListEulaAcceptances.build(context)
          when :list_eulas
            Aws::NimbleStudio::Endpoints::ListEulas.build(context)
          when :list_launch_profile_members
            Aws::NimbleStudio::Endpoints::ListLaunchProfileMembers.build(context)
          when :list_launch_profiles
            Aws::NimbleStudio::Endpoints::ListLaunchProfiles.build(context)
          when :list_streaming_images
            Aws::NimbleStudio::Endpoints::ListStreamingImages.build(context)
          when :list_streaming_sessions
            Aws::NimbleStudio::Endpoints::ListStreamingSessions.build(context)
          when :list_studio_components
            Aws::NimbleStudio::Endpoints::ListStudioComponents.build(context)
          when :list_studio_members
            Aws::NimbleStudio::Endpoints::ListStudioMembers.build(context)
          when :list_studios
            Aws::NimbleStudio::Endpoints::ListStudios.build(context)
          when :list_tags_for_resource
            Aws::NimbleStudio::Endpoints::ListTagsForResource.build(context)
          when :put_launch_profile_members
            Aws::NimbleStudio::Endpoints::PutLaunchProfileMembers.build(context)
          when :put_studio_members
            Aws::NimbleStudio::Endpoints::PutStudioMembers.build(context)
          when :start_streaming_session
            Aws::NimbleStudio::Endpoints::StartStreamingSession.build(context)
          when :start_studio_sso_configuration_repair
            Aws::NimbleStudio::Endpoints::StartStudioSSOConfigurationRepair.build(context)
          when :stop_streaming_session
            Aws::NimbleStudio::Endpoints::StopStreamingSession.build(context)
          when :tag_resource
            Aws::NimbleStudio::Endpoints::TagResource.build(context)
          when :untag_resource
            Aws::NimbleStudio::Endpoints::UntagResource.build(context)
          when :update_launch_profile
            Aws::NimbleStudio::Endpoints::UpdateLaunchProfile.build(context)
          when :update_launch_profile_member
            Aws::NimbleStudio::Endpoints::UpdateLaunchProfileMember.build(context)
          when :update_streaming_image
            Aws::NimbleStudio::Endpoints::UpdateStreamingImage.build(context)
          when :update_studio
            Aws::NimbleStudio::Endpoints::UpdateStudio.build(context)
          when :update_studio_component
            Aws::NimbleStudio::Endpoints::UpdateStudioComponent.build(context)
          end
        end
      end

      def add_handlers(handlers, _config)
        handlers.add(Handler, step: :build, priority: 75)
      end
    end
  end
end


text:
package com.tvd12.ezyfox.sfs2x.testing.command;

import static org.mockito.Mockito.*;

import java.lang.reflect.Field;

import org.testng.annotations.Test;

import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.api.APIManager;
import com.smartfoxserver.v2.api.ISFSBuddyResponseApi;
import com.smartfoxserver.v2.api.SFSBuddyApi;
import com.smartfoxserver.v2.api.response.ISFSResponseApi;
import com.smartfoxserver.v2.buddylist.Buddy;
import com.smartfoxserver.v2.buddylist.BuddyList;
import com.smartfoxserver.v2.buddylist.BuddyListManager;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSBuddyListException;
import com.tvd12.ezyfox.core.constants.APIKey;
import com.tvd12.ezyfox.core.entities.ApiUser;
import com.tvd12.ezyfox.core.reflect.ReflectFieldUtil;
import com.tvd12.ezyfox.sfs2x.command.impl.AddBuddyImpl;
import com.tvd12.ezyfox.sfs2x.testing.context.AppUser;

/**
 * @author tavandung12
 * Created on May 30, 2016
 *
 */
public class AddBuddyImplTest extends BaseCommandTest2 {

    @Test
    public void test() throws Exception {
        initEnviroment();
        AddBuddyImpl command = new AddBuddyImpl(context, api, extension);
        User sfsTargetUser = mock(User.class);
        ApiUser tartgetUser = new AppUser();
        tartgetUser.setName("buddy");
        when(sfsTargetUser.getProperty(APIKey.USER)).thenReturn(tartgetUser);
        when(api.getUserByName("buddy")).thenReturn(sfsTargetUser);
        when(sfsUser.getZone()).thenReturn(zone);

        BuddyListManager buddyListManager = mock(BuddyListManager.class);
        BuddyList buddyList = mock(BuddyList.class);
        when(buddyListManager.getBuddyList(USER_NAME)).thenReturn(buddyList);
        when(buddyListManager.isActive()).thenReturn(true);

        when(zone.getBuddyListManager()).thenReturn(buddyListManager);
        command.buddy("buddy")
            .fireClientEvent(true)
            .fireServerEvent(true)
            .owner(user)
            .owner(user.getName())
            .temp(false)
            .zone(apiZone)
            .execute();
    }

    @Test
    public void test2() throws Exception {
        initEnviroment();
        AddBuddyImpl command = new AddBuddyImpl(context, api, extension);
        User sfsTargetUser = mock(User.class);
        ApiUser tartgetUser = new AppUser();
        tartgetUser.setName("buddy1");
        when(sfsTargetUser.getProperty(APIKey.USER)).thenReturn(tartgetUser);
        when(api.getUserByName("buddy")).thenReturn(null);
        when(sfsUser.getZone()).thenReturn(zone);

        BuddyListManager buddyListManager = mock(BuddyListManager.class);
        BuddyList buddyList = mock(BuddyList.class);
        when(buddyListManager.getBuddyList(USER_NAME)).thenReturn(buddyList);
        when(buddyListManager.isActive()).thenReturn(true);

        when(zone.getBuddyListManager()).thenReturn(buddyListManager);
        command.buddy("buddy")
            .fireClientEvent(false)
            .fireServerEvent(false)
            .owner(user)
            .owner(user.getName())
            .temp(false)
            .zone(apiZone)
            .execute();
    }

    @Test(expectedExceptions = {IllegalStateException.class})
    public void test3() throws Exception {
        initEnviroment();
        AddBuddyImpl command = new AddBuddyImpl(context, api, extension);
        User sfsTargetUser = mock(User.class);
        ApiUser tartgetUser = new AppUser();
        tartgetUser.setName("buddy");
        when(sfsTargetUser.getProperty(APIKey.USER)).thenReturn(tartgetUser);
        when(api.getUserByName("buddy")).thenReturn(null);
        when(sfsUser.getZone()).thenReturn(zone);

        BuddyListManager buddyListManager = mock(BuddyListManager.class);
        BuddyList buddyList = mock(BuddyList.class);
        when(buddyListManager.getBuddyList(USER_NAME)).thenReturn(buddyList);
        when(buddyListManager.isActive()).thenReturn(false);

        when(zone.getBuddyListManager()).thenReturn(buddyListManager);
        command.buddy("buddy")
            .fireClientEvent(false)
            .fireServerEvent(false)
            .owner(user)
            .owner(user.getName())
            .temp(false)
            .zone(apiZone)
            .execute();
    }

    @Test
    public void test4() throws Exception {
        initEnviroment();
        AddBuddyImpl command = new AddBuddyImpl(context, api, extension);
        User sfsTargetUser = mock(User.class);
        ApiUser tartgetUser = new AppUser();
        tartgetUser.setName("buddy1");
        when(sfsTargetUser.getProperty(APIKey.USER)).thenReturn(tartgetUser);
        when(api.getUserByName("buddy")).thenReturn(null);
        when(sfsUser.getZone()).thenReturn(zone);

        BuddyListManager buddyListManager = mock(BuddyListManager.class);
        BuddyList buddyList = mock(BuddyList.class);
        doThrow(SFSBuddyListException.class).when(buddyList).addBuddy(any(Buddy.class));
        when(buddyListManager.getBuddyList(USER_NAME)).thenReturn(buddyList);
        when(buddyListManager.isActive()).thenReturn(true);

        when(zone.getBuddyListManager()).thenReturn(buddyListManager);

        ISFSResponseApi responseApi = mock(ISFSResponseApi.class);
        when(api.getResponseAPI()).thenReturn(responseApi);

        command.buddy("buddy")
            .fireClientEvent(false)
            .fireServerEvent(false)
            .owner(user)
            .owner(user.getName())
            .temp(false)
            .zone(apiZone)
            .execute();
    }

    @Test
    public void test5() throws Exception {
        initEnviroment();
        AddBuddyImpl command = new AddBuddyImpl(context, api, extension);
        User sfsTargetUser = mock(User.class);
        ApiUser tartgetUser = new AppUser();
        tartgetUser.setName("buddy1");
        when(sfsTargetUser.getProperty(APIKey.USER)).thenReturn(tartgetUser);
        when(api.getUserByName("buddy")).thenReturn(null);
        when(sfsUser.getZone()).thenReturn(zone);

        BuddyListManager buddyListManager = mock(BuddyListManager.class);
        BuddyList buddyList = mock(BuddyList.class);
        doThrow(SFSBuddyListException.class).when(buddyList).addBuddy(any(Buddy.class));
        when(buddyListManager.getBuddyList(USER_NAME)).thenReturn(buddyList);
        when(buddyListManager.isActive()).thenReturn(true);

        when(zone.getBuddyListManager()).thenReturn(buddyListManager);

        ISFSResponseApi responseApi = mock(ISFSResponseApi.class);
        when(api.getResponseAPI()).thenReturn(responseApi);

        command.buddy("buddy")
            .fireClientEvent(true)
            .fireServerEvent(true)
            .owner(user)
            .owner(user.getName())
            .temp(false)
            .zone(apiZone)
            .execute();
    }

    public void initEnviroment() throws Exception {
        APIManager apiManager = new APIManager();
        Field apiManagerField = ReflectFieldUtil.getField("apiManager", SmartFoxServer.class);
        apiManagerField.setAccessible(true);
        apiManagerField.set(SmartFoxServer.getInstance(), apiManager);
        apiManager.init(null);
        ISFSBuddyResponseApi responseApi = mock(ISFSBuddyResponseApi.class);
        Field responseApiField = ReflectFieldUtil.getField("responseAPI", SFSBuddyApi.class);
        responseApiField.setAccessible(true);
        responseApiField.set(apiManager.getBuddyApi(), responseApi);
    }

}


text:
<Type Name="NSView+Notifications" FullName="MonoMac.AppKit.NSView+Notifications">
  <TypeSignature Language="C#" Value="public static class NSView.Notifications" />
  <TypeSignature Language="ILAsm" Value=".class nested public auto ansi abstract sealed beforefieldinit NSView/Notifications extends System.Object" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="ObserveBoundsChanged">
      <MemberSignature Language="C#" Value="public static MonoMac.Foundation.NSObject ObserveBoundsChanged (EventHandler<MonoMac.Foundation.NSNotificationEventArgs> handler);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.Foundation.NSObject ObserveBoundsChanged(class System.EventHandler`1<class MonoMac.Foundation.NSNotificationEventArgs> handler) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSObject</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="handler" Type="System.EventHandler<MonoMac.Foundation.NSNotificationEventArgs>" />
      </Parameters>
      <Docs>
        <param name="handler">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ObserveFocusChanged">
      <MemberSignature Language="C#" Value="public static MonoMac.Foundation.NSObject ObserveFocusChanged (EventHandler<MonoMac.Foundation.NSNotificationEventArgs> handler);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.Foundation.NSObject ObserveFocusChanged(class System.EventHandler`1<class MonoMac.Foundation.NSNotificationEventArgs> handler) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSObject</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="handler" Type="System.EventHandler<MonoMac.Foundation.NSNotificationEventArgs>" />
      </Parameters>
      <Docs>
        <param name="handler">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ObserveFrameChanged">
      <MemberSignature Language="C#" Value="public static MonoMac.Foundation.NSObject ObserveFrameChanged (EventHandler<MonoMac.Foundation.NSNotificationEventArgs> handler);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.Foundation.NSObject ObserveFrameChanged(class System.EventHandler`1<class MonoMac.Foundation.NSNotificationEventArgs> handler) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSObject</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="handler" Type="System.EventHandler<MonoMac.Foundation.NSNotificationEventArgs>" />
      </Parameters>
      <Docs>
        <param name="handler">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ObserveGlobalFrameChanged">
      <MemberSignature Language="C#" Value="public static MonoMac.Foundation.NSObject ObserveGlobalFrameChanged (EventHandler<MonoMac.Foundation.NSNotificationEventArgs> handler);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.Foundation.NSObject ObserveGlobalFrameChanged(class System.EventHandler`1<class MonoMac.Foundation.NSNotificationEventArgs> handler) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSObject</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="handler" Type="System.EventHandler<MonoMac.Foundation.NSNotificationEventArgs>" />
      </Parameters>
      <Docs>
        <param name="handler">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ObserveUpdatedTrackingAreas">
      <MemberSignature Language="C#" Value="public static MonoMac.Foundation.NSObject ObserveUpdatedTrackingAreas (EventHandler<MonoMac.Foundation.NSNotificationEventArgs> handler);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.Foundation.NSObject ObserveUpdatedTrackingAreas(class System.EventHandler`1<class MonoMac.Foundation.NSNotificationEventArgs> handler) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSObject</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="handler" Type="System.EventHandler<MonoMac.Foundation.NSNotificationEventArgs>" />
      </Parameters>
      <Docs>
        <param name="handler">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
Title: Difference between ».apply()«, ».call()« and ».bind()« in JavaScript

-----

Date: 1428534307

-----

Authors: rasshofer

-----

Text:

When working with functions in JavaScript, the value of `this` and the functions' arguments are important. `.apply()`, `.call()` and `.bind()` allow you to change `this` inside a function and pass arguments in different ways.

The difference between `.apply()` and `.call()` is that `.apply()` lets you invoke the function with arguments as an array while `.call()` requires the arguments to be listed explicitly.

A useful mnemonic for this is…

- **a**pply() for arguments as an **a**rray
- **c**all() for **c**omma-separated arguments

Let's have a look at a simple example to understand what this means.

```js
function demo(name, age) {
    alert('My name is ' + name + ' and I am ' + age + ' years old');
}

demo('John', 25);

demo.apply(this, ['John', 25]);

demo.call(this, 'John', 25);
```

All three function calls above do exactly the same.  Both `.apply()` and `.call()` can be called on functions, which they run in the context (= the root scope in this case) of the first argument. Thus, you can use `.apply()` if you don't know the number of arguments you'll be passing or if the arguments are already in an array or array-like object (like the `arguments` object) and use `.call()` otherwise since there's no need to wrap the arguments in an array.

Whereas `.bind()` is used when you want a function to later be called with a certain context—which is useful in events. While `.apply()` and `.call()` call the function immediately, `.bind()` creates and returns a new function that—when executed later—will have the correct context (= bound to a different `this`) set for calling the original function. This way you can maintain context in asynchronous callbacks and events.

```js
var pollute = function () {
    this.innerHTML = 'Demo';
};

document.getElementById('demo').addEventListener('click', function () {
  window.setTimeout(pollute.bind(this), 1000);
});
```

You can also append extra parameters after the first parameter and `.bind()` will pass those values into the original function before passing in the extra parameters you pass to the bound function.

```js
var sum = function (a, b) {
    return a + b;
};

var addTo = sum.bind(this, 123);

console.log(addTo(456)); // = 579
```


text:
<?php

function copy_dir($src, $dst)
{
    $dir = opendir($src);
    if (!is_dir($dst))
        @mkdir($dst);
    while (($file = readdir($dir))) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file))
                copy_dir($src . '/' . $file, $dst . '/' . $file);
            else
                copy($src . '/' . $file, $dst . '/' . $file);
        }
    }
    closedir($dir);
}

$destination_folder = $argv[1];
if (empty($destination_folder))
    throw new \Exception("Please specify a destination folder");
if (!is_dir($destination_folder))
    throw new \Exception("destination folder $destination_folder not found");

$destination_folder .= '/FastBackground';
if (!is_dir($destination_folder))
    mkdir($destination_folder);

$src_dir = __DIR__;

foreach (
    [
        'config.php',
        'clear_cache_job.php',
        'fast_background.js',
        'fast_background.min.js',
        'get_img_without_js.php',
        'index.php',
        'init.php'
    ] as $f_name) {
    if (in_array($f_name, ['config.php']) and file_exists($destination_folder . '/' . $f_name)) {
        echo "$f_name skipping. File already exist\n";
        continue;
    }
    copy($src_dir . '/' . $f_name, $destination_folder . '/' . $f_name);
}
if (!file_exists($destination_folder . '/.gitignore'))
    copy($src_dir . '/gitignore', $destination_folder . '/.gitignore');
else
    echo ".gitignore skipping. File already exist\n";
copy_dir($src_dir . '/third_party_libs', $destination_folder . '/third_party_libs');


text:
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

import { HighlightJsModule } from 'ngx-highlight-js';

import { AutoCompleteDemoComponent } from './autocompletedemo.component';
import { AutoCompleteDemoRoutingModule } from './autocompletedemo-routing.module';
import { NewClientComponent } from './newclient/newclient.component';
import { DataClientService } from './newclient/dataclient.service';
import { DumpDataService } from '../../shared/services/dumpdata';
import { AutoCompleteModule } from '../../../../projects/truly-ui/src/components/autocomplete';
import { DialogModule } from '../../../../projects/truly-ui/src/components/dialog';
import { InputModule } from '../../../../projects/truly-ui/src/components/input';
import { FormModule } from '../../../../projects/truly-ui/src/components/form';
import { DropDownListModule } from '../../../../projects/truly-ui/src/components/dropdownlist';
import { ModalModule } from '../../../../projects/truly-ui/src/components/modal';
import { ShowcaseTablePropertiesModule } from '../../shared/components/showcase-table-properties/showcase-table-properties.module';
import { ShowcaseCardModule } from '../../shared/components/showcase-card/showcase-card.module';
import { ShowcaseTableEventsModule } from '../../shared/components/showcase-table-events/showcase-table-events.module';
import { ShowcaseReturnedValueModule } from '../../shared/components/showcase-returned-value/showcase-returned-value.module';
import { DialogService } from '../../../../projects/truly-ui/src/components/dialog/dialog.service';
import { PersonService } from './http.service';
import { HttpClientModule } from '@angular/common/http';
import { ShowcaseHeaderModule } from '../../shared/components/showcase-header/showcase-header.module';

@NgModule({
  declarations: [
    AutoCompleteDemoComponent,
    NewClientComponent
  ],
  imports: [
    AutoCompleteDemoRoutingModule,
    AutoCompleteModule,
    CommonModule,
    DialogModule,
    ReactiveFormsModule,
    FormsModule,
    InputModule,
    FormModule,
    DropDownListModule,
    AutoCompleteModule,
    ModalModule,
    HttpClientModule,
    HighlightJsModule,
    ShowcaseTablePropertiesModule,
    ShowcaseCardModule,
    ShowcaseTableEventsModule,
    ShowcaseReturnedValueModule,
    ShowcaseHeaderModule
  ],
  exports: [
    AutoCompleteDemoComponent,
  ],
  providers: [
    DialogService,
    DataClientService,
    DumpDataService,
    PersonService
  ],
  entryComponents: [ NewClientComponent ]
})
export class AutoCompleteDemoModule { }


text:
from qtpy.QtWidgets import QWidget, QSizePolicy

class FormBaseWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.setMaximumWidth(400)
        self.setMinimumWidth(400)

        sp = self.sizePolicy()
        sp.setVerticalPolicy(QSizePolicy.Minimum)
        self.setSizePolicy(sp)


text:
2013062101
==========
This dataset was captured as NAO wandered around a canteen area
containing tables, chairs and a pool table. NAO got a bit tangled up in
the chairs and wandered between two tables.

The dataset contains the following
* JSON files containing timestamps, left & right sonar values and the
  position and orientation of the NAO (6 DOF) in world coordinates
* JPEG files taken by NAO's camera at the time the data in each JSON
  file was captured.
* A video file captured by an external camera of NAO moving about the
  space. Please note that the time on the video is not aligned with the
  timestamps in the data.

The JSON and JPEG files have the same prefix and differ in
extension. Each file has a unique index after the common prefix which
identifies the dataset.