text:
#include <instantFSM.h>
#include <string.h>

#include "gtest/gtest.h"

using namespace ifsm;

/**
Canonical
*/
TEST(instantFSM, Canonical){
  StateMachine machine;
  ASSERT_FALSE(machine.inState("root"));
  machine.enter();
  ASSERT_TRUE(machine.inState("root"));
  machine.leave();
  ASSERT_FALSE(machine.inState("root"));
}

/**
RootOnEntry
*/
TEST(instantFSM, RootOnEntry){
  bool flag = false;
  StateMachine machine(
    OnEntry([&flag](){
      flag = true;
    })
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_TRUE(flag);

}
/**
RootOnExit
*/
TEST(instantFSM, RootOnExit){
  bool flag = false;
  StateMachine machine(
    OnExit([&flag](){
      flag = true;
    })
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.leave();

  ASSERT_TRUE(flag);

}
/**
RootOnEvent
*/
TEST(instantFSM, RootOnEvent){
  bool flag = false;
  StateMachine machine(
    OnEvent("event",[&flag](){
      flag = true;
    })
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.pushEvent("event");

  ASSERT_TRUE(flag);

}
/**
ChildOnEntry
*/
TEST(instantFSM, ChildOnEntry){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1", "S1B", "S1Biii" };

  StateMachine machine(
    State("S1", initialTag,
      OnEntry([&lXpResult](){
        lXpResult.push_back("S1");
      }),
      State("S1A",
        OnEntry([&lXpResult](){
          lXpResult.push_back("S1A");
        })
      ),
      State("S1B", initialTag,
        OnEntry([&lXpResult](){
          lXpResult.push_back("S1B");
        }),
        State("S1Bi",
          OnEntry([&lXpResult](){
            lXpResult.push_back("S1Bi");
          })
        ),
        State("S1Bii",
          OnEntry([&lXpResult](){
            lXpResult.push_back("S1Bii");
          })
        ),
        State("S1Biii", initialTag,
          OnEntry([&lXpResult](){
            lXpResult.push_back("S1Biii");
          })
        )
      ),
      State("S1C",
        OnEntry([&lXpResult](){
          lXpResult.push_back("S1C");
        })
      )
    ),
    State("S2",
      OnEntry([&lXpResult](){
        lXpResult.push_back("S2");
      })
    ),
    State("S3",
      OnEntry([&lXpResult](){
        lXpResult.push_back("S3");
      })
    )
  );

  ASSERT_TRUE(lXpResult.empty());

  machine.enter();

  ASSERT_EQ(lXpResult, lRefResult);

}
/**
ChildOnExit
*/
TEST(instantFSM, ChildOnExit){
  bool flag = false;

  StateMachine machine(
    State("S1", initialTag,
      OnExit([&flag](){
        flag = true;
      })
    )
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.leave();

  ASSERT_TRUE(flag);

}
/**
ChildOnEvent
*/
TEST(instantFSM, ChildOnEvent){
  bool flag = false;

  StateMachine machine(
    State("S1", initialTag,
      OnEvent("event",
        [&flag](){
          flag = true;
        }
      )
    )
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.pushEvent("event");

  ASSERT_TRUE(flag);

}
/**
TransitionOnExit
*/
TEST(instantFSM, TransitionOnExit){
  bool flag = false;

  StateMachine machine(
    State("S1", initialTag,
      Transition(OnEvent("event"),Target("S2")) ,
      OnExit([&flag](){
        flag = true;
      })
    ) ,
    State("S2")
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.pushEvent("event");

  ASSERT_TRUE(flag);

}
/**
TransitionAction
*/
TEST(instantFSM, TransitionAction){
  bool flag = false;

  StateMachine machine(
    State("S1", initialTag,
      Transition(
        OnEvent("event"),
        Target("S2"),
        Action([&flag](){
          flag = true;
        })
      )
    ) ,
    State("S2")
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.pushEvent("event");

  ASSERT_TRUE(flag);

}
/**
TransitionOnEntry
*/
TEST(instantFSM, TransitionOnEntry){
  bool flag = false;

  StateMachine machine(
    State("S1", initialTag,
      Transition(OnEvent("event"),Target("S2"))
    ) ,
    State("S2" ,
      OnEntry([&flag](){
        flag = true;
      })
    )
  );

  ASSERT_FALSE(flag);

  machine.enter();

  ASSERT_FALSE(flag);

  machine.pushEvent("event");

  ASSERT_TRUE(flag);

}
/**
CheckEntryOrder
*/
TEST(instantFSM, CheckEntryOrder){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1 entry", "S1A entry", "S1Ai entry" };

  StateMachine machine(
    State("S1", initialTag,
      OnEntry([&lXpResult](){
        lXpResult.push_back("S1 entry");
      }),
      State("S1A", initialTag,
        OnEntry([&lXpResult](){
          lXpResult.push_back("S1A entry");
        }),
        State("S1Ai", initialTag,
          OnEntry([&lXpResult](){
            lXpResult.push_back("S1Ai entry");
          })
        )
      )
    )
  );

  machine.enter();

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
CheckExitOrder
*/
TEST(instantFSM, CheckExitOrder){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1Ai exit", "S1A exit", "S1 exit" };

  StateMachine machine(
    State("S1", initialTag,
      OnExit([&lXpResult](){
        lXpResult.push_back("S1 exit");
      }),
      State("S1A", initialTag,
        OnExit([&lXpResult](){
          lXpResult.push_back("S1A exit");
        }),
        State("S1Ai", initialTag,
          OnExit([&lXpResult](){
            lXpResult.push_back("S1Ai exit");
          })
        ),
        State("S1Aii",
          OnExit([&lXpResult](){
            lXpResult.push_back("S1Aii exit");
          })
        )
      ),
      State("S1B",
        OnExit([&lXpResult](){
          lXpResult.push_back("S1B exit");
        }),
        State("S1Bi", initialTag,
          OnExit([&lXpResult](){
            lXpResult.push_back("S1Bi exit");
          })
        ),
        State("S1Bii",
          OnExit([&lXpResult](){
            lXpResult.push_back("S1Bii exit");
          })
        )
      )
    ),
    State("S2",
      OnExit([&lXpResult](){
        lXpResult.push_back("S2 exit");
      }),
      State("S2A", initialTag,
        OnExit([&lXpResult](){
          lXpResult.push_back("S2A exit");
        }),
        State("S2Ai", initialTag,
          OnExit([&lXpResult](){
            lXpResult.push_back("S2Ai exit");
          })
        ),
        State("S2Aii",
          OnExit([&lXpResult](){
            lXpResult.push_back("S2Aii exit");
          })
        )
      ),
      State("S2B",
        OnExit([&lXpResult](){
          lXpResult.push_back("S2B exit");
        }),
        State("S2Bi", initialTag,
          OnExit([&lXpResult](){
            lXpResult.push_back("S2Bi exit");
          })
        ),
        State("S2Bii",
          OnExit([&lXpResult](){
            lXpResult.push_back("S2Bii exit");
          })
        )
      )
    )
  );

  machine.enter();

  machine.leave();

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
TargetlessTransitions
*/
TEST(instantFSM, TargetlessTransitions){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "targetless in S1" , "OnEvent in S1" ,
    "targetless in S2A", "OnEvent in S2A"
  };

  StateMachine machine(parallelTag,
    State("S1",
      Transition(OnEvent("event"),
        Action([&lXpResult](){
          lXpResult.push_back("targetless in S1");
        })
      ),
      OnEvent("event",
        [&lXpResult](){
          lXpResult.push_back("OnEvent in S1");
        }
      )
    ),

    State("S2",

      Transition(OnEvent("event"),
        Action([&lXpResult](){
          lXpResult.push_back("targetless in S2");
        })
      ),
      OnEvent("event",
        [&lXpResult](){
          lXpResult.push_back("OnEvent in S2");
        }
      ),

      State("S2A", initialTag,
        Transition(OnEvent("event"),
          Action([&lXpResult](){
            lXpResult.push_back("targetless in S2A");
          })
        ),
        OnEvent("event",
          [&lXpResult](){
            lXpResult.push_back("OnEvent in S2A");
          }
        )
      ),

      State("S2B",
        Transition(OnEvent("event"),
          Action([&lXpResult](){
            lXpResult.push_back("targetless in S2B");
          })
        ),
        OnEvent("event",
          [&lXpResult](){
            lXpResult.push_back("OnEvent in S2B");
          }
        )
      )

    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S2"));
  ASSERT_TRUE(machine.inState("S2A"));
  ASSERT_FALSE(machine.inState("S2B"));

  machine.pushEvent("event");

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S2"));
  ASSERT_TRUE(machine.inState("S2A"));
  ASSERT_FALSE(machine.inState("S2B"));

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
CheckTransitionOrder
*/
TEST(instantFSM, CheckTransitionOrder){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "transition from S1A" };

  StateMachine machine(
    State("S1", initialTag,
      Transition(OnEvent("event"), Target("S2"), Action([&lXpResult](){
        lXpResult.push_back("transition from S1");
      })),
      State("S1A", initialTag,
        Transition(OnEvent("event"), Target("S2"), Action([&lXpResult](){
          lXpResult.push_back("transition from S1A");
        }))
      )
    ),
    State("S2")
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S1A"));
  ASSERT_FALSE(machine.inState("S2"));

  machine.pushEvent("event");

  ASSERT_FALSE(machine.inState("S1"));
  ASSERT_FALSE(machine.inState("S1A"));
  ASSERT_TRUE(machine.inState("S2"));

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
CheckParallelTransitionOrder
*/
TEST(instantFSM, CheckParallelTransitionOrder){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "transition from S1", "transition from S2" };

  StateMachine machine(parallelTag,
    State("S1",
      Transition(OnEvent("event"), Action([&lXpResult](){
        lXpResult.push_back("transition from S1");
      }))
    ),
    State("S2",
      Transition(OnEvent("event"), Action([&lXpResult](){
        lXpResult.push_back("transition from S2");
      }))
    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S2"));

  machine.pushEvent("event");

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S2"));

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
ParallelOnEntry
*/
TEST(instantFSM, ParallelOnEntry){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1", "S2", "S3" };

  StateMachine machine(parallelTag,
    State("S1",
      OnEntry([&lXpResult](){
        lXpResult.push_back("S1");
      })
    ),
    State("AAAAS2",
      OnEntry([&lXpResult](){
        lXpResult.push_back("S2");
      })
    ),
    State("ZZZZS2",
      OnEntry([&lXpResult](){
        lXpResult.push_back("S3");
      })
    )
  );

  machine.enter();

  ASSERT_EQ(lRefResult, lXpResult);
  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("AAAAS2"));
  ASSERT_TRUE(machine.inState("ZZZZS2"));

}

/**
ParallelOnExit
*/
TEST(instantFSM, ParallelOnExit){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S3", "S2", "S1" };

  StateMachine machine(parallelTag,
    State("S1",
      OnExit([&lXpResult](){
        lXpResult.push_back("S1");
      })
    ),
    State("AAAAS2",
      OnExit([&lXpResult](){
        lXpResult.push_back("S2");
      })
    ),
    State("ZZZZS2",
      OnExit([&lXpResult](){
        lXpResult.push_back("S3");
      })
    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("AAAAS2"));
  ASSERT_TRUE(machine.inState("ZZZZS2"));

  machine.leave();

  ASSERT_EQ(lRefResult, lXpResult);

}
/**
ParallelOnEvent
*/
TEST(instantFSM, ParallelOnEvent){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1", "S2", "S3" };

  StateMachine machine(parallelTag,
    State("S1",
      OnEvent("event",[&lXpResult](){
        lXpResult.push_back("S1");
      })
    ),
    State("AAAAS2",
      OnEvent("event", [&lXpResult](){
        lXpResult.push_back("S2");
      })
    ),
    State("ZZZZS2",
      OnEvent("event", [&lXpResult](){
        lXpResult.push_back("S3");
      })
    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("AAAAS2"));
  ASSERT_TRUE(machine.inState("ZZZZS2"));

  machine.pushEvent("event");

  ASSERT_EQ(lRefResult, lXpResult);

  machine.leave();

  ASSERT_FALSE(machine.inState("S1"));
  ASSERT_FALSE(machine.inState("AAAAS2"));
  ASSERT_FALSE(machine.inState("ZZZZS2"));

}

/**
TransitionToParallelChild
*/
TEST(instantFSM, TransitionToParallelChild){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1_entry", "S1_exit", "S1_to_S2B", "S2_entry", "S2A_entry", "S2B_entry" };

  StateMachine machine(
    State("S1", initialTag,
      OnEntry([&lXpResult](){
        lXpResult.push_back("S1_entry");
      }),
      Transition(
        OnEvent("event"),
        Target("S2B"),
        Action([&lXpResult](){
          lXpResult.push_back("S1_to_S2B");
        })
      ),
      OnExit([&lXpResult](){
        lXpResult.push_back("S1_exit");
      })
    ),
    State("S2", parallelTag,
      OnEntry([&lXpResult](){
        lXpResult.push_back("S2_entry");
      }),
      State("S2A",
        OnEntry([&lXpResult](){
          lXpResult.push_back("S2A_entry");
        })
      ),
      State("S2B",
        OnEntry([&lXpResult](){
          lXpResult.push_back("S2B_entry");
        })
      )
    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_FALSE(machine.inState("S2"));
  ASSERT_FALSE(machine.inState("S2A"));
  ASSERT_FALSE(machine.inState("S2B"));

  machine.pushEvent("event");

  ASSERT_FALSE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("S2"));
  ASSERT_TRUE(machine.inState("S2A"));
  ASSERT_TRUE(machine.inState("S2B"));

  ASSERT_EQ(lRefResult, lXpResult);

}

/**
ParallelConflictingTransition
*/
TEST(instantFSM, ParallelConflictingTransition){
  std::vector<std::string> lXpResult;
  std::vector<std::string> lRefResult = { "S1 entry", "SA entry", "SB entry", "SB exit", "SA exit", "S1 exit", "event", "S2 entry" };

  StateMachine machine(
    State("S1", parallelTag, initialTag,
      OnEntry([&lXpResult](){lXpResult.push_back("S1 entry");}),
      OnExit([&lXpResult](){lXpResult.push_back("S1 exit"); }),

      State("SA", //one transition targets S2
        OnEntry([&lXpResult](){lXpResult.push_back("SA entry"); }),
        OnExit([&lXpResult](){lXpResult.push_back("SA exit"); }),
        Transition(OnEvent("event"), Target("S2"), Action([&lXpResult](){
          lXpResult.push_back("event");
        }))
      ),

      State("SB",//while the other targets S3 on the same event
        OnEntry([&lXpResult](){lXpResult.push_back("SB entry"); }),
        OnExit([&lXpResult](){lXpResult.push_back("SB exit"); }),
        Transition(OnEvent("event"), Target("S3"), Action([&lXpResult](){
          lXpResult.push_back("event");
        }))
      )

    ),

    State("S2",
      OnEntry([&lXpResult](){lXpResult.push_back("S2 entry"); }),
      OnExit([&lXpResult](){lXpResult.push_back("S2 exit"); })
    ),

    State("S3",
      OnEntry([&lXpResult](){lXpResult.push_back("S3 entry"); }),
      OnExit([&lXpResult](){lXpResult.push_back("S3 exit"); })
    )
  );

  machine.enter();

  ASSERT_TRUE(machine.inState("S1"));
  ASSERT_TRUE(machine.inState("SA"));
  ASSERT_TRUE(machine.inState("SB"));
  ASSERT_FALSE(machine.inState("S2"));
  ASSERT_FALSE(machine.inState("S3"));

  machine.pushEvent("event");

  ASSERT_FALSE(machine.inState("S1"));
  ASSERT_FALSE(machine.inState("SA"));
  ASSERT_FALSE(machine.inState("SB"));
  ASSERT_TRUE(machine.inState("S2"));
  ASSERT_FALSE(machine.inState("S3"));

  ASSERT_EQ(lRefResult, lXpResult);

}

/**
TransitionBetweenParallel
*/

/**
Throws AlreadyHasInitial
*/

TEST(instantFSM, ThrowsAlreadyHasInitial){
  ASSERT_THROW(
  StateMachine machine(
    State("S1", initialTag),

    State("S2", initialTag)
  )
  , ifsm::AlreadyHasInitial);

}

/**
Throws DuplicateStateIdentifier
*/
TEST(instantFSM, ThrowsDuplicateStateIdentifier){
  ASSERT_THROW(
  StateMachine machine(
    State("S1", initialTag),

    State("S1")
  )
  , ifsm::DuplicateStateIdentifier);

}
/**
Throws NoInitialState
*/
TEST(instantFSM, ThrowsNoInitialState){
  ASSERT_THROW(
  StateMachine machine(
    State("S1"),

    State("S2")
  )
  , ifsm::NoInitialState);

}
/**
Throws NoSuchState
*/
TEST(instantFSM, ThrowsNoSuchState){
  ASSERT_THROW(
  StateMachine machine(
    State("S1", initialTag,
      Transition(
        OnEvent("event"),
        Target("doesnotexist")
      )
    )
  );
  , NoSuchState);

}
/**
Throws TargetAlreadySpecified
*/
TEST(instantFSM, ThrowsTargetAlreadySpecified){
  ASSERT_THROW(
    StateMachine machine(
      State("S1",
        Transition(
          OnEvent("event"),
          Target("S2"),
          Target("S3")
        )
      ),

      State("S2")
    )
    , ifsm::TargetAlreadySpecified);

}
/**
Throws ActionAlreadySpecified
*/
TEST(instantFSM, ThrowsActionAlreadySpecified){
  ASSERT_THROW(
    StateMachine machine(
      State("S1",
        Transition(
          OnEvent("event"),
          Action(
            std::function < void(void)>()
          ),
          Action(
            std::function < void(void)>()
          )
        )
      ),

      State("S2")
    )
    , ifsm::ActionAlreadySpecified);

}
/**
Throws ConditionAlreadySpecified
*/
TEST(instantFSM, ThrowsConditionAlreadySpecified){
  ASSERT_THROW(
    StateMachine machine(
      State("S1",
        Transition(
          OnEvent("event"),
          Condition(
            std::function < bool(void)>()
          ),
          Condition(
            std::function < bool(void)>()
          )
        )
      ),

      State("S2")
    )
    , ifsm::ConditionAlreadySpecified);

}
/**
Throws EventAlreadySpecified
*/

TEST(instantFSM, ThrowsEventAlreadySpecified){
  ASSERT_THROW(
    StateMachine machine(
      State("S1",
        Transition(
          OnEvent("event"),
          OnEvent("event2")
        )
      ),

      State("S2")
    )
    , ifsm::EventAlreadySpecified);

}

int main(int argc, char** argv){
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
<?php

namespace Faroca\Pizzapac\CartBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CartController extends Controller
{
    public function addProductAction($id)
    {

        //add product to cart.
        return $this->render('FarocaPizzapacCartBundle:Default:index.html.twig');
    }

    public function deleteProductAction($id)
    {

        //delete product to cart.
        return $this->render('FarocaPizzapacCartBundle:Default:index.html.twig');
    }

    public function refreshAction($id)
    {

        //refresh cart.
        return $this->render('FarocaPizzapacCartBundle:Default:index.html.twig');
    }
}

redpajama_set_name: RedPajamaGithub


text:
var setupTestHooks     = require('ember-cli-blueprint-test-helpers/lib/helpers/setup');
var BlueprintHelpers   = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper');
var generateAndDestroy = BlueprintHelpers.generateAndDestroy;

describe('Acceptance: generate and destroy transform blueprints', function() {
  setupTestHooks(this);

  it('transform', function() {
    return generateAndDestroy(['transform', 'foo'], {
      files: [
        {
          file: 'app/transforms/foo.js',
          contains: [
            'import Transform from \'ember-data/transform\';',
            'export default Transform.extend(',
            'deserialize(serialized) {',
            'serialize(deserialized) {'
          ]
        },
        {
          file: 'tests/unit/transforms/foo-test.js',
          contains: [
            'moduleFor(\'transform:foo\''
          ]
        }
      ]
    });
  });

  it('transforms-test', function() {
    return generateAndDestroy(['transform-test', 'foo'], {
      files: [
        {
          file: 'tests/unit/transforms/foo-test.js',
          contains: [
            'moduleFor(\'transform:foo\''
          ]
        }
      ]
    });
  });
});


text:
package com.caibowen.gplume.common;

/**
 * common codecs
 * @author BowenCai
 *
 */
public class Codecs {

	public static final class hex {

		private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();

		public static String toHexStr(byte[] bytes) {
			return new String(toHexChars(bytes));
		}

		public static char[] toHexChars(byte[] bytes) {
		    char[] hexChars = new char[bytes.length * 2];
		    for ( int j = 0; j < bytes.length; j++ ) {
		        int v = bytes[j] & 0xFF;
		        hexChars[j * 2] = HEX_CHARS[v >>> 4];
		        hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
		    }
		    return hexChars;
		}

        public static byte[] fromHexChars(char[] chars) {
            byte[] bytes = new byte[chars.length / 2];
            int len = chars.length;
            for (int i = 0, j = 0; j < len; i++) {
                int f = Character.digit(chars[j], 16) << 4;
                j++;
                f = f | Character.digit(chars[j], 16);
                j++;
                bytes[i] = (byte) (f & 0xFF);
            }
            return bytes;
        }

		public static byte[] fromStr(String s) {
		    int len = s.length();
		    byte[] data = new byte[len / 2];
		    for (int i = 0; i < len; i += 2) {
		        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
		                             + Character.digit(s.charAt(i+1), 16));
		    }
		    return data;
		}

		/** Mask for bit 0 of a byte. */
		private static final int BIT_0 = 1;

		/** Mask for bit 1 of a byte. */
		private static final int BIT_1 = 0x02;

		/** Mask for bit 2 of a byte. */
		private static final int BIT_2 = 0x04;

		/** Mask for bit 3 of a byte. */
		private static final int BIT_3 = 0x08;

		/** Mask for bit 4 of a byte. */
		private static final int BIT_4 = 0x10;

		/** Mask for bit 5 of a byte. */
		private static final int BIT_5 = 0x20;

		/** Mask for bit 6 of a byte. */
		private static final int BIT_6 = 0x40;

		/** Mask for bit 7 of a byte. */
		private static final int BIT_7 = 0x80;

		private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7};

		public static char[] toBinChars(final byte[] raw) {
			final char[] l_ascii = new char[raw.length << 3];
			for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) {
				for (int bits = 0; bits < BITS.length; ++bits) {
					if ((raw[ii] & BITS[bits]) == 0) {
						l_ascii[jj - bits] = '0';
					} else {
						l_ascii[jj - bits] = '1';
					}
				}
			}
			return l_ascii;
		}
		public static String toBinStr(final byte[] raw) {
			return new String(toBinChars(raw));
		}

		public static byte[] fromBinStr(String s) {
			return fromBinChars(s.toCharArray());
		}
		public static byte[] fromBinChars(final char[] ascii) {
			final byte[] l_raw = new byte[ascii.length >> 3];
			for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) {
				for (int bits = 0; bits < BITS.length; ++bits) {
					if (ascii[jj - bits] == '1') {
						l_raw[ii] |= BITS[bits];
					}
				}
			}
			return l_raw;
		}
	}

	public static class base64 {
	     /**
         * Encodes all bytes from the specified byte array into a newly-allocated
         * byte array using the {@link Base64} encoding scheme. The returned byte
         * array is of the length of the resulting bytes.
         *
         * @param   src
         *          the byte array to encode
         * @return  A newly-allocated byte array containing the resulting
         *          encoded bytes.
         */
        public static byte[] encode(byte[] src) {
        	return Base64.getEncoder().encode(src);
        }

        /**
         * Decodes all bytes from the input byte array using the {@link Base64}
         * encoding scheme, writing the results into a newly-allocated output
         * byte array. The returned byte array is of the length of the resulting
         * bytes.
         *
         * @param   src
         *          the byte array to decode
         *
         * @return  A newly-allocated byte array containing the decoded bytes.
         *
         * @throws  IllegalArgumentException
         *          if {@code src} is not in valid Base64 scheme
         */
        public static byte[] decode(byte[] src) {
        	return Base64.getDecoder().decode(src);
        }

        /**
         * Encodes the specified byte array into a String using the {@link Base64}
         * encoding scheme.
         *
         * <p> This method first encodes all input bytes into a base64 encoded
         * byte array and then constructs a new String by using the encoded byte
         * array and the {@link java.nio.charset.StandardCharsets#ISO_8859_1
         * ISO-8859-1} charset.
         *
         * <p> In other words, an invocation of this method has exactly the same
         * effect as invoking
         * {@code new String(encode(src), StandardCharsets.ISO_8859_1)}.
         *
         * @param   src
         *          the byte array to encode
         * @return  A String containing the resulting Base64 encoded characters
         */
        public static String encodeToString(byte[] src) {
        	return Base64.getEncoder().encodeToString(src);
        }

        /**
         * Decodes a Base64 encoded String into a newly-allocated byte array
         * using the {@link Base64} encoding scheme.
         *
         * <p> An invocation of this method has exactly the same effect as invoking
         * {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))}
         *
         * @param   src
         *          the string to decode
         *
         * @return  A newly-allocated byte array containing the decoded bytes.
         *
         * @throws  IllegalArgumentException
         *          if {@code src} is not in valid Base64 scheme
         */
        public static byte[] decode(String src) {
        	return Base64.getDecoder().decode(src);
        }
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Parasitol. , Paris, 1, 195.

#### Original name
null

### Remarks
null


text:
package com.imu.coursenet.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Student extends User implements Serializable {
	private static final long serialVersionUID = 48L;
	private Specialty specialty;
	private Set<Letter> letters = new HashSet<Letter>();
	public Student() {

	}

	public Student(Specialty specialty, Department department,
			String userAccount, String userPass, String userName,
			String userMail) {
		this.specialty = specialty;
		this.department = department;
		this.userAccount = userAccount;
		this.userPass = userPass;
		this.userName = userName;
		this.userMail = userMail;

	}

	public Set<Letter> getLetters() {
		return letters;
	}

	public void setLetters(Set<Letter> letters) {
		this.letters = letters;
	}

	public Specialty getSpecialty() {
		return specialty;
	}

	public void setSpecialty(Specialty specialty) {
		this.specialty = specialty;
	}
}


text:
import sys
import imp
import struct
import marshal

# these are .py modules
import imputil
import os

import pyjd

######################################################################

_TupleType = type(())
_StringType = type('')

######################################################################

# byte-compiled file suffic character
_suffix_char = __debug__ and 'c' or 'o'

# byte-compiled file suffix
_suffix = '.py' + _suffix_char

# the C_EXTENSION suffixes
_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())

from modcompile import PlatformParser, Module

pp = PlatformParser('platform', verbose=1)
pp.platform =  pyjd.engine
parser = PlatformParser(verbose=1, chain_plat=pp)

def _timestamp(pathname):
    "Return the file modification time as a Long."
    try:
        s = os.stat(pathname)
    except OSError:
        return None
    return long(s[8])

def _fs_import(dir, modname, fqname):
    "Fetch a module from the filesystem."

    pathname = os.path.join(dir, modname)
    if os.path.isdir(pathname):
        values = { '__pkgdir__' : pathname, '__path__' : [ pathname ] }
        ispkg = 1
        pathname = os.path.join(pathname, '__init__')
    else:
        values = { }
        ispkg = 0

        # look for dynload modules
        for desc in _c_suffixes:
            file = pathname + desc[0]
            try:
                fp = open(file, desc[1])
            except IOError:
                pass
            else:
                module = imp.load_module(fqname, fp, file, desc)
                values['__file__'] = file
                return 0, module, values

    t_py = _timestamp(pathname + '.py')
    t_pyc = _timestamp(pathname + _suffix)
    if t_py is None and t_pyc is None:
        return None
    code = None
    # XXX TODO - read .pyc from platform-specific locations...
    if False: # t_py is None or (t_pyc is not None and t_pyc >= t_py):
        file = pathname + _suffix
        f = open(file, 'rb')
        if f.read(4) == imp.get_magic():
            t = struct.unpack('<I', f.read(4))[0]
            if t == t_py:
                code = marshal.load(f)
        f.close()
    if code is None:
        file = pathname + '.py'
        mod, file = parser.parseModule(modname, file)
        code = Module(mod, file)
        code.compile()
        code = code.getCode()

        #code = imputil._compile(file, t_py)

    values['__file__'] = file
    return ispkg, code, values

######################################################################
#
# Simple function-based importer
#
class FuncImporter(imputil.Importer):
    "Importer subclass to delegate to a function rather than method overrides."
    def __init__(self, func):
        self.func = func
    def get_code(self, parent, modname, fqname):
        return self.func(parent, modname, fqname)

def install_with(func):
    FuncImporter(func).install()

######################################################################
#
# Base class for archive-based importing
#
class PackageArchiveImporter(imputil.Importer):
    """Importer subclass to import from (file) archives.

    This Importer handles imports of the style <archive>.<subfile>, where
    <archive> can be located using a subclass-specific mechanism and the
    <subfile> is found in the archive using a subclass-specific mechanism.

    This class defines two hooks for subclasses: one to locate an archive
    (and possibly return some context for future subfile lookups), and one
    to locate subfiles.
    """

    def get_code(self, parent, modname, fqname):
        if parent:
            # the Importer._finish_import logic ensures that we handle imports
            # under the top level module (package / archive).
            assert parent.__importer__ == self

            # if a parent "package" is provided, then we are importing a
            # sub-file from the archive.
            result = self.get_subfile(parent.__archive__, modname)
            if result is None:
                return None
            if isinstance(result, _TupleType):
                assert len(result) == 2
                return (0,) + result
            return 0, result, {}

        # no parent was provided, so the archive should exist somewhere on the
        # default "path".
        archive = self.get_archive(modname)
        if archive is None:
            return None
        return 1, "", {'__archive__':archive}

    def get_archive(self, modname):
        """Get an archive of modules.

        This method should locate an archive and return a value which can be
        used by get_subfile to load modules from it. The value may be a simple
        pathname, an open file, or a complex object that caches information
        for future imports.

        Return None if the archive was not found.
        """
        raise RuntimeError, "get_archive not implemented"

    def get_subfile(self, archive, modname):
        """Get code from a subfile in the specified archive.

        Given the specified archive (as returned by get_archive()), locate
        and return a code object for the specified module name.

        A 2-tuple may be returned, consisting of a code object and a dict
        of name/values to place into the target module.

        Return None if the subfile was not found.
        """
        raise RuntimeError, "get_subfile not implemented"

class PackageArchive(PackageArchiveImporter):
    "PackageArchiveImporter subclass that refers to a specific archive."

    def __init__(self, modname, archive_pathname):
        self.__modname = modname
        self.__path = archive_pathname

    def get_archive(self, modname):
        if modname == self.__modname:
            return self.__path
        return None

    # get_subfile is passed the full pathname of the archive

######################################################################
#
# Emulate the standard directory-based import mechanism
#
class DirectoryImporter(imputil.Importer):
    "Importer subclass to emulate the standard importer."

    def __init__(self, dir):
        self.dir = dir

    def get_code(self, parent, modname, fqname):
        if parent:
            dir = parent.__pkgdir__
        else:
            dir = self.dir

        # Return the module (and other info) if found in the specified
        # directory. Otherwise, return None.
        return _fs_import(dir, modname, fqname)

    def __repr__(self):
        return '<%s.%s for "%s" at 0x%x>' % (self.__class__.__module__,
                                             self.__class__.__name__,
                                             self.dir,
                                             id(self))

######################################################################
#
# Emulate the standard path-style import mechanism
#
class PathImporter(imputil.Importer):
    def __init__(self, path=sys.path):
        self.path = path

    def get_code(self, parent, modname, fqname):
        #print "PathImporter.get_code", parent, modname, fqname
        if parent:
            # we are looking for a module inside of a specific package
            return _fs_import(parent.__pkgdir__, modname, fqname)

        # scan sys.path, looking for the requested module
        for dir in self.path:
            if isinstance(dir, _StringType):
                result = _fs_import(dir, modname, fqname)
                if result:
                    return result

        # not found
        return None

######################################################################

def _test_dir():
    "Debug/test function to create DirectoryImporters from sys.path."
    imputil.ImportManager().install()
    path = sys.path[:]
    path.reverse()
    for d in path:
        sys.path.insert(0, DirectoryImporter(d))
    sys.path.insert(0, imputil.BuiltinImporter())

def _test_revamp():
    "Debug/test function for the revamped import system."
    imputil.ImportManager().install()
    sys.path.insert(0, PathImporter())
    sys.path.insert(0, imputil.BuiltinImporter())


text:
#if !defined(TIMEMAN_H_INCLUDED)
#define TIMEMAN_H_INCLUDED

struct SearchLimits;

class TimeManager {
public:

  void init(const SearchLimits& limits, int currentPly);
  void pv_instability(int curChanges, int prevChanges);
  int available_time() const { return optimumSearchTime + unstablePVExtraTime; }
  int maximum_time() const { return maximumSearchTime; }

private:
  int optimumSearchTime;
  int maximumSearchTime;
  int unstablePVExtraTime;
};

#endif // !defined(TIMEMAN_H_INCLUDED)


text:
#include "OgreSDLWindow.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreImageCodec.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#   include <windows.h>
#   include <wingdi.h>
#   include <GL/gl.h>
#   define GL_GLEXT_PROTOTYPES
#   include "glprocs.h"
#   include <GL/glu.h>
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
#   include <GL/gl.h>
#   include <GL/glu.h>
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#   include <OpenGL/gl.h>
#   define GL_EXT_texture_env_combine 1
#   include <OpenGL/glext.h>
#   include <OpenGL/glu.h>
#endif

namespace Ogre {

    SDLWindow::SDLWindow() :
        mScreen(NULL), mActive(false), mClosed(false)
    {
    }

    SDLWindow::~SDLWindow()
    {
        // according to http://www.libsdl.org/cgi/docwiki.cgi/SDL_5fSetVideoMode
        // never free the surface returned from SDL_SetVideoMode
        /*if (mScreen != NULL)
            SDL_FreeSurface(mScreen);*/

    }

	void SDLWindow::create(const String& name, unsigned int width, unsigned int height,
	            bool fullScreen, const NameValuePairList *miscParams)
    {
		int colourDepth = 32;
		String title = name;
		if(miscParams)
		{
			// Parse miscellenous parameters
			NameValuePairList::const_iterator opt;
			// Bit depth
			opt = miscParams->find("colourDepth");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
				colourDepth = StringConverter::parseUnsignedInt(opt->second);
			// Full screen antialiasing
			opt = miscParams->find("FSAA");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
			{
				size_t fsaa_x_samples = StringConverter::parseUnsignedInt(opt->second);
				if(fsaa_x_samples>1) {
					// If FSAA is enabled in the parameters, enable the MULTISAMPLEBUFFERS
					// and set the number of samples before the render window is created.
					SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
					SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,fsaa_x_samples);
				}
			}
			// Window title
			opt = miscParams->find("title");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
				title = opt->second;
		}

        LogManager::getSingleton().logMessage("SDLWindow::create", LML_TRIVIAL);
        SDL_Surface* screen;
        int flags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE;

        SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
        // request good stencil size if 32-bit colour
        if (colourDepth == 32)
        {
            SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8);
        }

        if (fullScreen)
            flags |= SDL_FULLSCREEN;

        LogManager::getSingleton().logMessage("Create window", LML_TRIVIAL);
        screen = SDL_SetVideoMode(width, height, colourDepth, flags);
        if (!screen)
        {
            LogManager::getSingleton().logMessage(LML_CRITICAL,
                String("Could not make screen: ") + SDL_GetError());
            exit(1);
        }
        LogManager::getSingleton().logMessage("screen is valid", LML_TRIVIAL);
        mScreen = screen;

        mName = name;

        mWidth = width;
        mHeight = height;

        mActive = true;

        if (!fullScreen)
            SDL_WM_SetCaption(title.c_str(), 0);

        glXGetVideoSyncSGI = (int (*)(unsigned int *))SDL_GL_GetProcAddress("glXGetVideoSyncSGI");
        glXWaitVideoSyncSGI = (int (*)(int, int, unsigned int *))SDL_GL_GetProcAddress("glXWaitVideoSyncSGI");
    }

    void SDLWindow::destroy(void)
    {
        // according to http://www.libsdl.org/cgi/docwiki.cgi/SDL_5fSetVideoMode
        // never free the surface returned from SDL_SetVideoMode
        //SDL_FreeSurface(mScreen);
        mScreen = NULL;
        mActive = false;

        Root::getSingleton().getRenderSystem()->detachRenderTarget( this->getName() );
    }

    bool SDLWindow::isActive() const
    {
        return mActive;
    }

    bool SDLWindow::isClosed() const
    {
        return mClosed;
    }

    void SDLWindow::reposition(int left, int top)
    {
        // XXX FIXME
    }

    void SDLWindow::resize(unsigned int width, unsigned int height)
    {
        SDL_Surface* screen;
        int flags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE;

        LogManager::getSingleton().logMessage("Updating window", LML_TRIVIAL);
        screen = SDL_SetVideoMode(width, height, mScreen->format->BitsPerPixel, flags);
        if (!screen)
        {
            LogManager::getSingleton().logMessage(LML_CRITICAL,
                String("Could not make screen: ") + SDL_GetError());
            exit(1);
        }
        LogManager::getSingleton().logMessage("screen is valid", LML_TRIVIAL);
        mScreen = screen;

        mWidth = width;
        mHeight = height;

        for (ViewportList::iterator it = mViewportList.begin();
             it != mViewportList.end(); ++it)
        {
            (*it).second->_updateDimensions();
        }
    }

    void SDLWindow::setVSyncEnabled(bool vsync)
	{
        mVSync = vsync;
	}

	bool SDLWindow::isVSyncEnabled() const
	{
        return mVSync;
	}

    void SDLWindow::swapBuffers()
    {
        if ( mVSync && glXGetVideoSyncSGI && glXWaitVideoSyncSGI )
        {
            unsigned int retraceCount;
            glXGetVideoSyncSGI( &retraceCount );
            glXWaitVideoSyncSGI( 2, ( retraceCount + 1 ) & 1, &retraceCount);
        }

        SDL_GL_SwapBuffers();
        // XXX More?
    }

	void SDLWindow::copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer)
	{
		if ((dst.left < 0) || (dst.right > mWidth) ||
			(dst.top < 0) || (dst.bottom > mHeight) ||
			(dst.front != 0) || (dst.back != 1))
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
						"Invalid box.",
						"SDLWindow::copyContentsToMemory" );
		}

		if (buffer == FB_AUTO)
		{
			buffer = mIsFullScreen? FB_FRONT : FB_BACK;
		}

		GLenum format = Ogre::GLPixelUtil::getGLOriginFormat(dst.format);
		GLenum type = Ogre::GLPixelUtil::getGLOriginDataType(dst.format);

		if ((format == GL_NONE) || (type == 0))
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
						"Unsupported format.",
						"SDLWindow::copyContentsToMemory" );
		}

		// Switch context if different from current one
		RenderSystem* rsys = Root::getSingleton().getRenderSystem();
		rsys->_setViewport(this->getViewport(0));

        if(dst.getWidth() != dst.rowPitch)
            glPixelStorei(GL_PACK_ROW_LENGTH, dst.rowPitch);
		// Must change the packing to ensure no overruns!
		glPixelStorei(GL_PACK_ALIGNMENT, 1);

		glReadBuffer((buffer == FB_FRONT)? GL_FRONT : GL_BACK);
        glReadPixels((GLint)0, (GLint)(mHeight - dst.getHeight()),
                     (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(),
                     format, type, dst.getTopLeftFrontPixelPtr());

		// restore default alignment
		glPixelStorei(GL_PACK_ALIGNMENT, 4);
        glPixelStorei(GL_PACK_ROW_LENGTH, 0);

        PixelUtil::bulkPixelVerticalFlip(dst);
	}
}


text:
Fetch is the canonical way to do HTTP requests in the browser, and it can be used in other environments such as React Native. Jest Fetch Mock allows you to easily mock your `fetch` calls and return the response you need to fake the HTTP requests. It's easy to setup and you don't need a library like `nock` to get going and it uses Jest's built-in support for mocking under the surface. This means that any of the `jest.fn()` methods are also available. For more information on the jest mock API, check their docs [here](https://facebook.github.io/jest/docs/en/mock-functions.html)

It currently supports the mocking with the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) polyfill, so it supports Node.js and any browser-like runtime.

## Contents

- [Usage](#usage)
  - [Installation and Setup](#installation-and-setup)
  - [Using with Create-React-App](#using-with-create-react-app)
- [API](#api)
- [Examples](#examples)
  - [Simple mock and assert](#simple-mock-and-assert)
  - [Mocking all fetches](#mocking-all-fetches)
  - [Mocking a failed fetch](#mocking-a-failed-fetch)
  - [Mocking multiple fetches with different responses](#mocking-multiple-fetches-with-different-responses)
  - [Mocking multiple fetches with `fetch.mockResponses`](#mocking-multiple-fetches-with-fetchmockresponses)
  - [Reset mocks between tests with `fetch.resetMocks`](#reset-mocks-between-tests-with-fetchresetmocks)
  - [Using `fetch.mock` to inspect the mock state of each fetch call](#using-fetchmock-to-inspect-the-mock-state-of-each-fetch-call)
  - [Using functions to mock slow servers](#using-functions-to-mock-slow-servers)

## Usage

### Package Installation

To setup your fetch mock you need to do the following things:

```
$ npm install --save-dev jest-fetch-mock
```

Create a `setupJest` file to setup the mock or add this to an existing `setupFile`. :

### To setup for all tests

```js
//setupJest.js or similar file
require('jest-fetch-mock').enableMocks()
```

Add the setupFile to your jest config in `package.json`:

```JSON
"jest": {
  "automock": false,
  "setupFiles": [
    "./setupJest.js"
  ]
}
```

With this done, you'll have `fetch` and `fetchMock` available on the global scope. Fetch will be used as usual by your code and you'll use `fetchMock` in your tests

#### Default not mocked

If you would like to have the 'fetchMock' available in all tests but not enabled then add `fetchMock.dontMock()` after the `...enableMocks()` line in `setupJest.js`:
```js
// adds the 'fetchMock' global variable and rewires 'fetch' global to call 'fetchMock' instead of the real implementation
require('jest-fetch-mock').enableMocks()
// changes default behavior of fetchMock to use the real 'fetch' implementation and not mock responses
fetchMock.dontMock()
```
If you want a single test file to return to the default behavior of mocking all responses, add the following to the
test file:
```js
beforeEach(() => { // if you have an existing `beforeEach` just add the following line to it
  fetchMock.doMock()
})
```

To enable mocking for a specific URL only:
```js
beforeEach(() => { // if you have an existing `beforeEach` just add the following lines to it
  fetchMock.mockIf(/^https?:\/\/example.com.*$/, req => {
      if (req.url.endsWith("/path1")) {
        return "some response body"
      } else if (req.url.endsWith("/path2")) {
        return {
          body: "another response body",
          headers: {
            "X-Some-Response-Header": "Some header value"
          }
        }
      } else {
        return {
          status: 404,
          body: "Not Found"
        }
      }
  })
})
```

If you have changed the default behavior to use the real implementation, you can guarantee the next call to fetch
will be mocked by using the `mockOnce` function:
```js
fetchMock.mockOnce("the next call to fetch will always return this as the body")
```

This function behaves exactly like `fetchMock.once` but guarantees the next call to `fetch` will be mocked even if the
default behavior of fetchMock is to use the real implementation.  You can safely convert all you `fetchMock.once` calls
to `fetchMock.mockOnce` without a risk of changing their behavior.

### To setup for an individual test

For JavaScript add the following line to the start of your test case (before any other requires)
```js
require('jest-fetch-mock').enableMocks()
```

For TypeScript/ES6 add the following lines to the start of your test case (before any other imports)
```typescript
import { enableFetchMocks } from 'jest-fetch-mock'
enableFetchMocks()
```

#### TypeScript importing

If you are using TypeScript and receive errors about the `fetchMock` global not existing,
add a `global.d.ts` file to the root of your project (or add the following line to an existing global file):

```typescript
import 'jest-fetch-mock'
```

If you prefer you can also just import the fetchMock in a test case.
```typescript
import fetchMock from "jest-fetch-mock"
```

You may also need to edit your `tsconfig.json` and add "dom" and/or "es2015" and/or "esnext" to the 'compilerConfig.lib' property

### Using with Create-React-App

If you are using [Create-React-App](https://github.com/facebookincubator/create-react-app) (CRA), the code for `setupTest.js` above should be placed into `src/setupTests.js` in the root of your project. CRA automatically uses this filename by convention in the Jest configuration it generates. Similarly, changing to your `package.json` is not required as CRA handles this when generating your Jest configuration.

### For Ejected Create React Apps _ONLY_:

> Note: Keep in mind that if you decide to "eject" before creating src/setupTests.js, the resulting package.json file won't contain any reference to it, so you should manually create the property setupTestFrameworkScriptFile in the configuration for Jest, something like the [following](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#srcsetuptestsjs-1):

```JSON
"jest": {
  "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js"
 }
```

## API

### Mock Responses

- `fetch.mockResponse(bodyOrFunction, init): fetch` - Mock all fetch calls
- `fetch.mockResponseOnce(bodyOrFunction, init): fetch` - Mock each fetch call independently
- `fetch.once(bodyOrFunction, init): fetch` - Alias for `mockResponseOnce(bodyOrFunction, init)`
- `fetch.mockResponses(...responses): fetch` - Mock multiple fetch calls independently
  - Each argument is an array taking `[bodyOrFunction, init]`
- `fetch.mockReject(errorOrFunction): fetch` - Mock all fetch calls, letting them fail directly
- `fetch.mockRejectOnce(errorOrFunction): fetch` - Let the next fetch call fail directly
- `fetch.mockAbort(): fetch` - Causes all fetch calls to reject with an "Aborted!" error
- `fetch.mockAbortOnce(): fetch` - Causes the next fetch call to reject with an "Aborted!" error

### Functions

Instead of passing body, it is also possible to pass a function that returns a promise.
The promise should resolve with a string or an object containing body and init props

i.e:

```js
fetch.mockResponse(() => callMyApi().then(res => ({ body: 'ok' })))
// OR
fetch.mockResponse(() => callMyApi().then(res => 'ok'))
```

The function may take an optional "request" parameter of type `http.Request`:

```js
fetch.mockResponse(req =>
  req.url === 'http://myapi/'
    ? callMyApi().then(res => 'ok')
    : Promise.reject(new Error('bad url'))
)
```

Note: the request "url" is parsed and then printed using the equivalent of `new URL(input).href` so it may not match exactly with the URL's passed to `fetch` if they are not fully qualified.
For example, passing "http://foo.com" to `fetch` will result in the request URL being "http://foo.com/" (note the trailing slash).

The same goes for rejects:

```js
fetch.mockReject(() =>
  doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
)
// OR
fetch.mockReject(req =>
  req.headers.get('content-type') === 'text/plain'
    ? Promise.reject('invalid content type')
    : doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
)
```

### Mock utilities

- `fetch.resetMocks()` - Clear previously set mocks so they do not bleed into other mocks
- `fetch.enableMocks()` - Enable fetch mocking by overriding `global.fetch` and mocking `node-fetch`
- `fetch.disableMocks()` - Disable fetch mocking and restore default implementation of `fetch` and/or `node-fetch`
- `fetch.mock` - The mock state for your fetch calls. Make assertions on the arguments given to `fetch` when called by the functions you are testing. For more information check the [Jest docs](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)

For information on the arguments body and init can take, you can look at the MDN docs on the Response Constructor function, which `jest-fetch-mock` uses under the surface.

https://developer.mozilla.org/en-US/docs/Web/API/Response/Response

Each mocked response or err
or will return a [Mock Function](http://facebook.github.io/jest/docs/mock-function-api.html#content). You can use methods like `.toHaveBeenCalledWith` to ensure that the mock function was called with specific arguments. For more methods detail, take a look at [this](http://facebook.github.io/jest/docs/expect.html#content).

## Examples

In most of the complicated examples below, I am testing my action creators in Redux, but it doesn't have to be used with Redux.

### Simple mock and assert

In this simple example I won't be using any libraries. It is a simple fetch request, in this case to google.com. First we setup the `beforeEach` callback to reset our mocks. This isn't strictly necessary in this example, but since we will probably be mocking fetch more than once, we need to reset it across our tests to assert on the arguments given to fetch.

Once we've done that we can start to mock our response. We want to give it an objectwith a `data` property and a string value of `12345` and wrap it in `JSON.stringify` to JSONify it. Here we use `mockResponseOnce`, but we could also use `once`, which is an alias for a call to `mockResponseOnce`

We then call the function that we want to test with the arguments we want to test with. In the `then` callback we assert we have got the correct data back.

Finally we can assert on the `.mock` state that Jest provides for us to test what arguments were given to fetch and how many times it was called

```js
//api.js
export function APIRequest(who) {
  if (who === 'google') {
    return fetch('https://google.com').then(res => res.json())
  } else {
    return 'no argument provided'
  }
}
```

```js
//api.test.js
import { APIRequest } from './api'

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('calls google and returns data to me', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }))

    //assert on the response
    APIRequest('google').then(res => {
      expect(res.data).toEqual('12345')
    })

    //assert on the times called and arguments given to fetch
    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('https://google.com')
  })
})
```

### Mocking all fetches

In this example I am mocking just one fetch call. Any additional fetch calls in the same function will also have the same mock response. For more complicated functions with multiple fetch calls, you can check out example 3.

```js
import configureMockStore from 'redux-mock-store' // mock store
import thunk from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

import { getAccessToken } from './accessToken'

describe('Access token action creators', () => {
  it('dispatches the correct actions on successful fetch request', () => {
    fetch.mockResponse(JSON.stringify({ access_token: '12345' }))

    const expectedActions = [
      { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } }
    ]
    const store = mockStore({ config: { token: '' } })

    return (
      store
        .dispatch(getAccessToken())
        //getAccessToken contains the fetch call
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})
```

### Mocking a failed fetch

In this example I am mocking just one fetch call but this time using the `mockReject` function to simulate a failed request. Any additional fetch calls in the same function will also have the same mock response. For more complicated functions with multiple fetch calls, you can check out example 3.

```js
import configureMockStore from 'redux-mock-store' // mock store
import thunk from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

import { getAccessToken } from './accessToken'

describe('Access token action creators', () => {
  it('dispatches the correct actions on a failed fetch request', () => {
    fetch.mockReject(new Error('fake error message'))

    const expectedActions = [
      { type: 'SET_ACCESS_TOKEN_FAILED', error: { status: 503 } }
    ]
    const store = mockStore({ config: { token: '' } })

    return (
      store
        .dispatch(getAccessToken())
        //getAccessToken contains the fetch call
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})
```

### Mocking aborted fetches

Fetches can be mocked to act as if they were aborted during the request.  This can be done in 4 ways:

Using `fetch.mockAborted()`

Using `fetch.mockAbortedOnce()`

Passing a request (or request init) with a 'signal' to fetch that has been aborted

Passing a request (or request init) with a 'signal' to fetch and a async function to `fetch.mockResponse` or `fetch.mockResponseOnce` that causes the signal to abort before returning the response

```js
describe('Mocking aborts', () => {
  beforeEach(() => {
    fetch.resetMocks()
    fetch.doMock()
    jest.useFakeTimers()
  })
  afterEach(() => {
    jest.useRealTimers()
  })

  it('rejects with an Aborted! Error', () => {
    fetch.mockAbort()
    expect(fetch('/')).rejects.toThrow('Aborted!')
  })
  it('rejects with an Aborted! Error once then mocks with empty response', async () => {
    fetch.mockAbortOnce()
    await expect(fetch('/')).rejects.toThrow('Aborted!')
    await expect(request()).resolves.toEqual('')
  })

  it('throws when passed an already aborted abort signal', () => {
    const c = new AbortController()
    c.abort()
    expect(() => fetch('/', { signal: c.signal })).toThrow('Aborted!')
  })

  it('rejects when aborted before resolved', async () => {
    const c = new AbortController()
    fetch.mockResponse(async () => {
      jest.advanceTimersByTime(60)
      return ''
    })
    setTimeout(() => c.abort(), 50)
    await expect(fetch('/', { signal: c.signal })).rejects.toThrow('Aborted!')
  })
})
```

### Mocking multiple fetches with different responses

In this next example, the store does not yet have a token, so we make a request to get an access token first. This means that we need to mock two different responses, one for each of the fetches. Here we can use `fetch.mockResponseOnce` or `fetch.once` to mock the response only once and call it twice. Because we return the mocked function, we can chain this jQuery style. It internally uses Jest's `mockImplementationOnce`. You can read more about it on the [Jest documentation](https://facebook.github.io/jest/docs/mock-functions.html#content)

```js
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

import { getAnimeDetails } from './animeDetails'

describe('Anime details action creators', () => {
  it('dispatches requests for an access token before requesting for animeDetails', () => {
    fetch
      .once(JSON.stringify({ access_token: '12345' }))
      .once(JSON.stringify({ name: 'naruto' }))

    const expectedActions = [
      { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } },
      { type: 'SET_ANIME_DETAILS', animeDetails: { name: 'naruto' } }
    ]
    const store = mockStore({ config: { token: null } })

    return (
      store
        .dispatch(getAnimeDetails('21049'))
        //getAnimeDetails contains the 2 fetch calls
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})
```

### Mocking multiple fetches with `fetch.mockResponses`

`fetch.mockResponses` takes as many arguments as you give it, all of which are arrays representing each Response Object. It will then call the `mockImplementationOnce` for each response object you give it. This reduces the amount of boilerplate code you need to write. An alternative is to use `.once` and chain it multiple times if you don't like wrapping each response arguments in a tuple/array.

In this example our actionCreator calls `fetch` 4 times, once for each season of the year and then concatenates the results into one final array. You'd have to write `fetch.mockResponseOnce` 4 times to achieve the same thing:

```js
describe('getYear action creator', () => {
  it('dispatches the correct actions on successful getSeason fetch request', () => {
    fetch.mockResponses(
      [
        JSON.stringify([{ name: 'naruto', average_score: 79 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'bleach', average_score: 68 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'one piece', average_score: 80 }]),
        { status: 200 }
      ],
      [
        JSON.stringify([{ name: 'shingeki', average_score: 91 }]),
        { status: 200 }
      ]
    )

    const expectedActions = [
      {
        type: 'FETCH_ANIMELIST_REQUEST'
      },
      {
        type: 'SET_YEAR',
        payload: {
          animes: [
            { name: 'naruto', average_score: 7.9 },
            { name: 'bleach', average_score: 6.8 },
            { name: 'one piece', average_score: 8 },
            { name: 'shingeki', average_score: 9.1 }
          ],
          year: 2016
        }
      },
      {
        type: 'FETCH_ANIMELIST_COMPLETE'
      }
    ]
    const store = mockStore({
      config: {
        token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }
      },
      years: []
    })

    return (
      store
        .dispatch(getYear(2016))
        //This calls fetch 4 times, once for each season
        .then(() => {
          // return of async actions
          expect(store.getActions()).toEqual(expectedActions)
        })
    )
  })
})
```

### Reset mocks between tests with `fetch.resetMocks`

`fetch.resetMocks` resets the `fetch` mock to give fresh mock data in between tests. It only resets the `fetch` calls as to not disturb any other mocked functionality.

```js
describe('getYear action creator', () => {
  beforeEach(() => {
      fetch.resetMocks();
  });
  it('dispatches the correct actions on successful getSeason fetch request', () => {

    fetch.mockResponses(
      [
        JSON.stringify([ {name: 'naruto', average_score: 79} ]), { status: 200}
      ],
      [
        JSON.stringify([ {name: 'bleach', average_score: 68} ]), { status: 200}
      ]
    )

    const expectedActions = [
      {
        type: 'FETCH_ANIMELIST_REQUEST'
      },
      {
        type: 'SET_YEAR',
        payload: {
          animes: [
            {name: 'naruto', average_score: 7.9},
            {name: 'bleach', average_score: 6.8}
          ],
          year: 2016,
        }
      },
      {
        type: 'FETCH_ANIMELIST_COMPLETE'
      }
    ]
    const store = mockStore({
      config: { token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }},
      years: []
    })

    return store.dispatch(getYear(2016))
      //This calls fetch 2 times, once for each season
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  });
  it('dispatches the correct actions on successful getSeason fetch request', () => {

    fetch.mockResponses(
      [
        JSON.stringify([ {name: 'bleach', average_score: 68} ]), { status: 200}
      ],
      [
        JSON.stringify([ {name: 'one piece', average_score: 80} ]), { status: 200}
      ],
      [
        JSON.stringify([ {name: 'shingeki', average_score: 91} ]), { status: 200}
      ]
    )

    const expectedActions = [
      {
        type: 'FETCH_ANIMELIST_REQUEST'
      },
      {
        type: 'SET_YEAR',
        payload: {
          animes: [
            {name: 'bleach', average_score: 6.8},
            {name: 'one piece', average_score: 8},
            {name: 'shingeki', average_score: 9.1}
          ],
          year: 2016,
        }
      },
      {
        type: 'FETCH_ANIMELIST_COMPLETE'
      }
    ]
    const store = mockStore({
      config: { token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }},
      years: []
    })

    return store.dispatch(getYear(2016))
      //This calls fetch 3 times, once for each season
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
      ,

  })
})
```

### Using `fetch.mock` to inspect the mock state of each fetch call

`fetch.mock` by default uses [Jest's mocking functions](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property). Therefore you can make assertions on the mock state. In this example we have an arbitrary function that makes a different fetch request based on the argument you pass to it. In our test, we run Jest's `beforeEach()` and make sure to reset our mock before each `it()` block as we will make assertions on the arguments we are passing to `fetch()`. The most uses property is the `fetch.mock.calls` array. It can give you information on each call, and their arguments which you can use for your `expect()` calls. Jest also comes with some nice aliases for the most used ones.

```js
// api.js

import 'cross-fetch'

export function APIRequest(who) {
  if (who === 'facebook') {
    return fetch('https://facebook.com')
  } else if (who === 'twitter') {
    return fetch('https://twitter.com')
  } else {
    return fetch('https://google.com')
  }
}
```

```js
// api.test.js
import { APIRequest } from './api'

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks()
  })

  it('calls google by default', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest()

    expect(fetch.mock.calls.length).toEqual(1)
    expect(fetch.mock.calls[0][0]).toEqual('https://google.com')
  })

  it('calls facebook', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest('facebook')

    expect(fetch.mock.calls.length).toEqual(2)
    expect(fetch.mock.calls[0][0]).toEqual(
      'https://facebook.com/someOtherResource'
    )
    expect(fetch.mock.calls[1][0]).toEqual('https://facebook.com')
  })

  it('calls twitter', () => {
    fetch.mockResponse(JSON.stringify({ secret_data: '12345' }))
    APIRequest('twitter')

    expect(fetch).toBeCalled() // alias for expect(fetch.mock.calls.length).toEqual(1);
    expect(fetch).toBeCalledWith('https://twitter.com') // alias for expect(fetch.mock.calls[0][0]).toEqual();
  })
})
```

### Using functions to mock slow servers

By default you will want to have your fetch mock return immediately. However if you have some custom logic that needs to tests for slower servers, you can do this by passing it a function and returning a promise when your function resolves

```js
// api.test.js
import { request } from './api'

describe('testing timeouts', () => {
  it('resolves with function and timeout', async () => {
    fetch.mockResponseOnce(
      () =>
        new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }), 100))
    )
    try {
      const response = await request()
      expect(response).toEqual('ok')
    } catch (e) {
      throw e
    }
  })
})
```

### Conditional Mocking

In some test scenarios, you may want to temporarily disable (or enable) mocking for all requests or the next (or a certain number of) request(s).
You may want to only mock fetch requests to some URLs that match a given request path while in others you may want to mock
all requests except those matching a given request path. You may even want to conditionally mock based on request headers.

The conditional mock functions cause `jest-fetch-mock` to pass fetches through to the concrete fetch implementation conditionally.
Calling `fetch.dontMock`, `fetch.doMock`, `fetch.doMockIf` or `fetch.dontMockIf` overrides the default behavior
of mocking/not mocking all requests. `fetch.dontMockOnce`, `fetch.doMockOnce`, `fetch.doMockOnceIf` and `fetch.dontMockOnceIf` only overrides the behavior
for the next call to `fetch`, then returns to the default behavior (either mocking all requests or mocking the requests based on the last call to
`fetch.dontMock`, `fetch.doMock`, `fetch.doMockIf` and `fetch.dontMockIf`).

Calling `fetch.resetMocks()` will return to the default behavior of mocking all fetches with a text response of empty string.

- `fetch.dontMock()` - Change the default behavior to not mock any fetches until `fetch.resetMocks()` or `fetch.doMock()` is called
- `fetch.doMock(bodyOrFunction?, responseInit?)` - Reverses `fetch.dontMock()`. This is the default state after `fetch.resetMocks()`
- `fetch.dontMockOnce()` - For the next fetch, do not mock then return to the default behavior for subsequent fetches. Can be chained.
- `fetch.doMockOnce(bodyOrFunction?, responseInit?)` or `fetch.mockOnce` - For the next fetch, mock the response then return to the default behavior for subsequent fetches. Can be chained.
- `fetch.doMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch` or `fetch.mockIf` - causes all fetches to be not be mocked unless they match the given string/RegExp/predicate
  (i.e. "only mock 'fetch' if the request is for the given URL otherwise, use the real fetch implementation")
- `fetch.dontMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch` - causes all fetches to be mocked unless they match the given string/RegExp/predicate
  (i.e. "don't mock 'fetch' if the request is for the given URL, otherwise mock the request")
- `fetch.doMockOnceIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch` or `fetch.mockOnceIf` - causes the next fetch to be mocked if it matches the given string/RegExp/predicate. Can be chained.
  (i.e. "only mock 'fetch' if the next request is for the given URL otherwise, use the default behavior")
- `fetch.dontMockOnceIf(urlOrPredicate):fetch` - causes the next fetch to be not be mocked if it matches the given string/RegExp/predicate. Can be chained.
  (i.e. "don't mock 'fetch' if the next request is for the given URL, otherwise use the default behavior")
- `fetch.isMocking(input, init):boolean` - test utility function to see if the given url/request would be mocked.
  This is not a read only operation and any "MockOnce" will evaluate (and return to the default behavior)

For convenience, all the conditional mocking functions also accept optional parameters after the 1st parameter that call
  `mockResponse` or `mockResponseOnce` respectively.  This allows you to conditionally mock a response in a single call.

#### Conditional Mocking examples
```js

describe('conditional mocking', () => {
  const realResponse = 'REAL FETCH RESPONSE'
  const mockedDefaultResponse = 'MOCKED DEFAULT RESPONSE'
  const testUrl = defaultRequestUri
  let crossFetchSpy
  beforeEach(() => {
    fetch.resetMocks()
    fetch.mockResponse(mockedDefaultResponse)
    crossFetchSpy = jest
      .spyOn(require('cross-fetch'), 'fetch')
      .mockImplementation(async () =>
        Promise.resolve(new Response(realResponse))
      )
  })

  afterEach(() => {
    crossFetchSpy.mockRestore()
  })

  const expectMocked = async (uri, response = mockedDefaultResponse) => {
    return expect(request(uri)).resolves.toEqual(response)
  }
  const expectUnmocked = async uri => {
    return expect(request(uri)).resolves.toEqual(realResponse)
  }

  describe('once', () => {
    it('default', async () => {
      const otherResponse = 'other response'
      fetch.once(otherResponse)
      await expectMocked(defaultRequestUri, otherResponse)
      await expectMocked()
    })
    it('dont mock once then mock twice', async () => {
      const otherResponse = 'other response'
      fetch
        .dontMockOnce()
        .once(otherResponse)
        .once(otherResponse)

      await expectUnmocked()
      await expectMocked(defaultRequestUri, otherResponse)
      await expectMocked()
    })
  })

  describe('doMockIf', () => {
    it("doesn't mock normally", async () => {
      fetch.doMockIf('http://foo')
      await expectUnmocked()
      await expectUnmocked()
    })
    it('mocks when matches string', async () => {
      fetch.doMockIf(testUrl)
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches regex', async () => {
      fetch.doMockIf(new RegExp(testUrl))
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches predicate', async () => {
      fetch.doMockIf(input => input.url === testUrl)
      await expectMocked()
      await expectMocked()
    })
  })

  describe('dontMockIf', () => {
    it('mocks normally', async () => {
      fetch.dontMockIf('http://foo')
      await expectMocked()
      await expectMocked()
    })
    it('doesnt mock when matches string', async () => {
      fetch.dontMockIf(testUrl)
      await expectUnmocked()
      await expectUnmocked()
    })
    it('doesnt mock when matches regex', async () => {
      fetch.dontMockIf(new RegExp(testUrl))
      await expectUnmocked()
      await expectUnmocked()
    })
    it('doesnt mock when matches predicate', async () => {
      fetch.dontMockIf(input => input.url === testUrl)
      await expectUnmocked()
      await expectUnmocked()
    })
  })

  describe('doMockOnceIf (default mocked)', () => {
    it("doesn't mock normally", async () => {
      fetch.doMockOnceIf('http://foo')
      await expectUnmocked()
      await expectMocked()
    })
    it('mocks when matches string', async () => {
      fetch.doMockOnceIf(testUrl)
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches regex', async () => {
      fetch.doMockOnceIf(new RegExp(testUrl))
      await expectMocked()
      await expectMocked()
    })
    it('mocks when matches predicate', async () => {
      fetch.doMockOnceIf(input => input.url === testUrl)
      await expectMocked()
      await expectMocked()
    })
  })

  describe('dontMockOnceIf (default mocked)', () => {
    it('mocks normally', async () => {
      fetch.dontMockOnceIf('http://foo')
      await expectMocked()
      await expectMocked()
    })
    it('doesnt mock when matches string', async () => {
      fetch.dontMockOnceIf(testUrl)
      await expectUnmocked()
      await expectMocked()
    })
    it('doesnt mock when matches regex', async () => {
      fetch.dontMockOnceIf(new RegExp(testUrl))
      await expectUnmocked()
      await expectMocked()
    })
    it('doesnt mock when matches predicate', async () => {
      fetch.dontMockOnceIf(input => input.url === testUrl)
      await expectUnmocked()
      await expectMocked()
    })
  })

  describe('doMockOnceIf (default unmocked)', () => {
    beforeEach(() => {
      fetch.dontMock()
    })
    it("doesn't mock normally", async () => {
      fetch.doMockOnceIf('http://foo')
      await expectUnmocked()
      await expectUnmocked()
    })
    it('mocks when matches string', async () => {
      fetch.doMockOnceIf(testUrl)
      await expectMocked()
      await expectUnmocked()
    })
    it('mocks when matches regex', async () => {
      fetch.doMockOnceIf(new RegExp(testUrl))
      await expectMocked()
      await expectUnmocked()
    })
    it('mocks when matches predicate', async () => {
      fetch.doMockOnceIf(input => input.url === testUrl)
      await expectMocked()
      await expectUnmocked()
    })
  })

  describe('dontMockOnceIf (default unmocked)', () => {
    beforeEach(() => {
      fetch.dontMock()
    })
    it('mocks normally', async () => {
      fetch.dontMockOnceIf('http://foo')
      await expectMocked()
      await expectUnmocked()
    })
    it('doesnt mock when matches string', async () => {
      fetch.dontMockOnceIf(testUrl)
      await expectUnmocked()
      await expectUnmocked()
    })
    it('doesnt mock when matches regex', async () => {
      fetch.dontMockOnceIf(new RegExp(testUrl))
      await expectUnmocked()
      await expectUnmocked()
    })
    it('doesnt mock when matches predicate', async () => {
      fetch.dontMockOnceIf(input => input.url === testUrl)
      await expectUnmocked()
      await expectUnmocked()
    })
  })

  describe('dont/do mock', () => {
    test('dontMock', async () => {
      fetch.dontMock()
      await expectUnmocked()
      await expectUnmocked()
    })
    test('dontMockOnce', async () => {
      fetch.dontMockOnce()
      await expectUnmocked()
      await expectMocked()
    })
    test('doMock', async () => {
      fetch.dontMock()
      fetch.doMock()
      await expectMocked()
      await expectMocked()
    })
    test('doMockOnce', async () => {
      fetch.dontMock()
      fetch.doMockOnce()
      await expectMocked()
      await expectUnmocked()
    })
  })

```

```js
const expectMocked = async (uri, response = mockedDefaultResponse) => {
  return expect(request(uri)).resolves.toEqual(response)
}
const expectUnmocked = async uri => {
  return expect(request(uri)).resolves.toEqual(realResponse)
}

describe('conditional mocking complex', () => {
  const realResponse = 'REAL FETCH RESPONSE'
  const mockedDefaultResponse = 'MOCKED DEFAULT RESPONSE'
  const testUrl = defaultRequestUri
  let crossFetchSpy
  beforeEach(() => {
    fetch.resetMocks()
    fetch.mockResponse(mockedDefaultResponse)
    crossFetchSpy = jest
      .spyOn(require('cross-fetch'), 'fetch')
      .mockImplementation(async () =>
        Promise.resolve(new Response(realResponse))
      )
  })

  afterEach(() => {
    crossFetchSpy.mockRestore()
  })

  describe('complex example', () => {
    const alternativeUrl = 'http://bar'
    const alternativeBody = 'ALTERNATIVE RESPONSE'
    beforeEach(() => {
      fetch
        // .mockResponse(mockedDefaultResponse) // set above - here for clarity
        .mockResponseOnce('1') // 1
        .mockResponseOnce('2') // 2
        .mockResponseOnce(async uri =>
          uri === alternativeUrl ? alternativeBody : '3'
        ) // 3
        .mockResponseOnce('4') // 4
        .mockResponseOnce('5') // 5
        .mockResponseOnce(async uri =>
          uri === alternativeUrl ? alternativeBody : mockedDefaultResponse
        ) // 6
    })

    describe('default (`doMock`)', () => {
      beforeEach(() => {
        fetch
          // .doMock()    // the default - here for clarify
          .dontMockOnceIf(alternativeUrl)
          .doMockOnceIf(alternativeUrl)
          .doMockOnce()
          .dontMockOnce()
      })

      test('defaultRequestUri', async () => {
        await expectMocked(defaultRequestUri, '1') // 1
        await expectUnmocked(defaultRequestUri) // 2
        await expectMocked(defaultRequestUri, '3') // 3
        await expectUnmocked(defaultRequestUri) // 4
        // after .once('..')
        await expectMocked(defaultRequestUri, '5') // 5
        await expectMocked(defaultRequestUri, mockedDefaultResponse) // 6
        // default 'isMocked' (not 'Once')
        await expectMocked(defaultRequestUri, mockedDefaultResponse) // 7
      })

      test('alternativeUrl', async () => {
        await expectUnmocked(alternativeUrl) // 1
        await expectMocked(alternativeUrl, '2') // 2
        await expectMocked(alternativeUrl, alternativeBody) // 3
        await expectUnmocked(alternativeUrl) // 4
        // after .once('..')
        await expectMocked(alternativeUrl, '5') // 5
        await expectMocked(alternativeUrl, alternativeBody) // 6
        // default 'isMocked' (not 'Once')
        await expectMocked(alternativeUrl, mockedDefaultResponse) // 7
      })
    })

    describe('dontMock', () => {
      beforeEach(() => {
        fetch
          .dontMock()
          .dontMockOnceIf(alternativeUrl)
          .doMockOnceIf(alternativeUrl)
          .doMockOnce()
          .dontMockOnce()
      })

      test('defaultRequestUri', async () => {
        await expectMocked(defaultRequestUri, '1') // 1
        await expectUnmocked(defaultRequestUri) // 2
        await expectMocked(defaultRequestUri, '3') // 3
        await expectUnmocked(defaultRequestUri) // 4
        // after .once('..')
        await expectUnmocked(defaultRequestUri) // 5
        await expectUnmocked(defaultRequestUri) // 6
        // default 'isMocked' (not 'Once')
        await expectUnmocked(defaultRequestUri) // 7
      })

      test('alternativeUrl', async () => {
        await expectUnmocked(alternativeUrl) // 1
        await expectMocked(alternativeUrl, '2') // 2
        await expectMocked(alternativeUrl, alternativeBody) // 3
        await expectUnmocked(alternativeUrl) // 4
        // after .once('..')
        await expectUnmocked(alternativeUrl) // 5
        await expectUnmocked(alternativeUrl) // 6
        // default 'isMocked' (not 'Once')
        await expectUnmocked(alternativeUrl) // 7
      })
    })

    describe('doMockIf(alternativeUrl)', () => {
      beforeEach(() => {
        fetch
          .doMockIf(alternativeUrl)
          .dontMockOnceIf(alternativeUrl)
          .doMockOnceIf(alternativeUrl)
          .doMockOnce()
          .dontMockOnce()
      })

      test('defaultRequestUri', async () => {
        await expectMocked(defaultRequestUri, '1') // 1
        await expectUnmocked(defaultRequestUri) // 2
        await expectMocked(defaultRequestUri, '3') // 3
        await expectUnmocked(defaultRequestUri) // 4
        // after .once('..')
        await expectUnmocked(defaultRequestUri) // 5
        await expectUnmocked(defaultRequestUri) // 6
        // default 'isMocked' (not 'Once')
        await expectUnmocked(defaultRequestUri) // 7
      })

      test('alternativeUrl', async () => {
        await expectUnmocked(alternativeUrl) // 1
        await expectMocked(alternativeUrl, '2') // 2
        await expectMocked(alternativeUrl, alternativeBody) // 3
        await expectUnmocked(alternativeUrl) // 4
        // after .once('..')
        await expectMocked(alternativeUrl, '5') // 5
        await expectMocked(alternativeUrl, alternativeBody) // 6
        // default 'isMocked' (not 'Once')
        await expectMocked(alternativeUrl, mockedDefaultResponse) // 7
      })
    })

    describe('dontMockIf(alternativeUrl)', () => {
      beforeEach(() => {
        fetch
          .dontMockIf(alternativeUrl)
          .dontMockOnceIf(alternativeUrl)
          .doMockOnceIf(alternativeUrl)
          .doMockOnce()
          .dontMockOnce()
      })

      test('defaultRequestUri', async () => {
        await expectMocked(defaultRequestUri, '1') // 1
        await expectUnmocked(defaultRequestUri) // 2
        await expectMocked(defaultRequestUri, '3') // 3
        await expectUnmocked(defaultRequestUri) // 4
        // after .once('..')
        await expectMocked(defaultRequestUri, '5') // 5
        await expectMocked(defaultRequestUri, mockedDefaultResponse) // 6
        // default 'isMocked' (not 'Once')
        await expectMocked(defaultRequestUri, mockedDefaultResponse) // 7
      })

      test('alternativeUrl', async () => {
        await expectUnmocked(alternativeUrl) // 1
        await expectMocked(alternativeUrl, '2') // 2
        await expectMocked(alternativeUrl, alternativeBody) // 3
        await expectUnmocked(alternativeUrl) // 4
        // after .once('..')
        await expectUnmocked(alternativeUrl) // 5
        await expectUnmocked(alternativeUrl) // 6
        // default 'isMocked' (not 'Once')
        await expectUnmocked(alternativeUrl) // 7
      })
    })
  })
})
```


text:
"""Contains a metaclass and helper functions used to create
protocol message classes from Descriptor objects at runtime.

Recall that a metaclass is the "type" of a class.
(A class is to a metaclass what an instance is to a class.)

In this case, we use the GeneratedProtocolMessageType metaclass
to inject all the useful functionality into the classes
output by the protocol compiler at compile-time.

The upshot of all this is that the real implementation
details for ALL pure-Python protocol buffers are *here in
this file*.
"""

__author__ = 'robinson@google.com (Will Robinson)'

from google.protobuf.internal import api_implementation
from google.protobuf import message

if api_implementation.Type() == 'cpp':
  from google.protobuf.pyext import cpp_message as message_impl
else:
  from google.protobuf.internal import python_message as message_impl

# The type of all Message classes.
# Part of the public interface.
#
# Used by generated files, but clients can also use it at runtime:
#   mydescriptor = pool.FindDescriptor(.....)
#   class MyProtoClass(Message):
#     __metaclass__ = GeneratedProtocolMessageType
#     DESCRIPTOR = mydescriptor
GeneratedProtocolMessageType = message_impl.GeneratedProtocolMessageType

def ParseMessage(descriptor, byte_str):
  """Generate a new Message instance from this Descriptor and a byte string.

  Args:
    descriptor: Protobuf Descriptor object
    byte_str: Serialized protocol buffer byte string

  Returns:
    Newly created protobuf Message object.
  """
  result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg

def MakeClass(descriptor):
  """Construct a class object for a protobuf described by descriptor.

  Composite descriptors are handled by defining the new class as a member of the
  parent class, recursing as deep as necessary.
  This is the dynamic equivalent to:

  class Parent(message.Message):
    __metaclass__ = GeneratedProtocolMessageType
    DESCRIPTOR = descriptor
    class Child(message.Message):
      __metaclass__ = GeneratedProtocolMessageType
      DESCRIPTOR = descriptor.nested_types[0]

  Sample usage:
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(proto2_string)
    msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
    msg_class = reflection.MakeClass(msg_descriptor)
    msg = msg_class()

  Args:
    descriptor: A descriptor.Descriptor object describing the protobuf.
  Returns:
    The Message class object described by the descriptor.
  """
  attributes = {}
  for name, nested_type in list(descriptor.nested_types_by_name.items()):
    attributes[name] = MakeClass(nested_type)

  attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor

  return GeneratedProtocolMessageType(str(descriptor.name), (message.Message,),
                                      attributes)


text:
namespace Ui {
class StartSettingDialog;
}

class StartSettingDialog : public QDialog
{
  Q_OBJECT

public:
  explicit StartSettingDialog(QWidget *parent = 0);
  ~StartSettingDialog();

  QString getWorkDir();
  void setWorkDir(const QString &dir);

private slots:
  void on_pushButton_clicked();

private:
  Ui::StartSettingDialog *ui;
};

#endif // STARTSETTINGDIALOG_H


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Omphalia campanella var. terrestris Quél.

### Remarks
null


text:
'use strict';

const angular = require('angular');

import {PIPELINE_CONFIG_SERVICE} from 'core/pipeline/config/services/pipelineConfig.service';

module.exports = angular.module('spinnaker.core.pipeline.config.actions.enable', [
  PIPELINE_CONFIG_SERVICE,
])
  .controller('EnablePipelineModalCtrl', function($uibModalInstance, pipelineConfigService, pipeline) {

    this.viewState = {};

    this.pipelineName = pipeline.name;

    this.cancel = $uibModalInstance.dismiss;

    this.enablePipeline = () => {
      pipeline.disabled = false;
      return pipelineConfigService.savePipeline(pipeline).then(
        () => $uibModalInstance.close(),
        (response) => {
          this.viewState.saveError = true;
          this.viewState.errorMessage = response.message || 'No message provided';
        }
      );
    };

  });


text:
/*jshint browser:true, devel:true */
/*global jQuery, wp, document, wpml_language_switcher_admin, _, iclSaveForm_success_cb, iclSaveForm */
var WPML_core = WPML_core || {};

WPML_core.languageSwitcher = (function( $, wpml_ls ) {
	"use strict";

	/** @namespace wpml_ls.strings */
	/** @namespace wpml_ls.strings.confirmation_item_remove */
	/** @namespace wpml_ls.color_schemes */
	/** @namespace wpml_ls.strings.table_no_item */
	/** @namespace wpml_ls.templates */

	var form,
		dialogBox,
		formAndDialogBox,
		additionalCssStyleId = 'wpml-ls-inline-styles-additional-css',
		dialogInlineStyleId  = 'wpml-ls-inline-styles-dialog',
		currentItemSlug,
		slotInlineStylesBackup;

	var init = function () {
		form         	 = $('#wpml-ls-settings-form');
		dialogBox        = $('#wpml-ls-dialog');
		formAndDialogBox = form.add(dialogBox);

		maybeInitAdditionalCssStyle();
		initDialogNode();
		initColorPicker();
		initLanguageSortable();
		attachEvents();
		openDialogFromHash();
		$(document).trigger('wpml_ls_admin_loaded');
	};

	var attachEvents = function () {
		attachAutoSaveEvents();
		attachToggleEvents();
		attachTooltipEvents();
		attachDialogEvents();
		attachRowActionEvents();
		attachSelectedSlotChangeEvents();
		attachPresetColorsEvent();
		attachTemplateChangeEvents();
		attachMenuHierarchicalEvents();
		attachUpdatePreviewEvents();
		attachSaveClickEvents();
		fixSelectedOption();
		forceRefreshOnBrowserBackButton();
		setupWizardNextEvent();
		preventClickOnPreviewLinks();
	};

	var maybeInitAdditionalCssStyle = function() {
		if ($('#' + additionalCssStyleId).length < 1) {
			var style = $('');

				$('#' + styleId).replaceWith(newStyleNode);
			});
	};

	var attachTemplateChangeEvents = function() {
		formAndDialogBox.on('change', '.js-wpml-ls-template-selector', function() {
			var selected = $(this).val(),
				subform  = $(this).closest('.js-wpml-ls-subform'),
				force    = wpml_ls.templates[ selected ].force_settings;

			subform.find('.js-wpml-ls-to-include input').prop('disabled', false);

			jQuery.each(force, function(k, v){
				if(v === 1) {
					subform.find('.js-wpml-ls-setting-' + k).attr('checked', 'checked').prop('disabled', true);
				} else {
					subform.find('.js-wpml-ls-setting-' + k).removeAttr('checked').prop('disabled', true);
				}
			});
		});
	};

	var attachMenuHierarchicalEvents = function() {
		formAndDialogBox.on('change', '.js-wpml-ls-menu-is-hierarchical', function() {
			var isHierarchical          = parseInt($(this).val()),
				subform                 = $(this).closest('.js-wpml-ls-subform'),
				includeCurrentLangInput = subform.find('.js-wpml-ls-setting-display_link_for_current_lang');

			includeCurrentLangInput.prop('disabled', false);

			if(isHierarchical === 1) {
				includeCurrentLangInput.attr('checked', 'checked').prop('disabled', true);
			}
		});
	};

	var updatePreview = _.debounce( function(subform) {
		$('.js-wpml-ls-dialog-save').prop('disabled', true);
		var preview = subform.find('.js-wpml-ls-preview');

		if(preview.length > 0) {
			showSpinner(preview);
			var previewData = getSerializedSettings(subform);

			wp.ajax.send({
				data: {
					action:        'wpml-ls-update-preview',
					nonce:         wpml_ls.nonce,
					slot_settings: previewData
				},
				success:  function (data) {
					preview.empty();
					updateDialogInlineStyle(data.styles);
					buildCSSLinks(data.css);
					buildJSScripts(data.js);
					showUpdatedContent(preview, data.html);
				},
				error: function (data) {
					showUpdatedContent(preview, data, 0, 'error');
				}
			});
		}
	}, 500);

	var attachSaveClickEvents = function() {
		form.on('click', '.js-wpml-ls-save-settings', function(e){
			e.preventDefault();
			updateSettings($(this));
		});
	};

	var updateSettings = _.debounce(function (wrapper, successCallback) {
		var messageWrapper = wrapper.closest('.js-wpml-ls-option').find('.js-wpml-ls-messages'),
			settings       = getSerializedSettings(form);

		if(messageWrapper.length === 0) {
			messageWrapper = wrapper.closest('.js-wpml-ls-section').find('.js-wpml-ls-messages');
		}

		messageWrapper.empty();
		showSpinner(messageWrapper);

		wp.ajax.send({
			data: {
				action:   'wpml-ls-save-settings',
				nonce:    wpml_ls.nonce,
				settings: settings
			},
			success:  function (data) {
				showUpdatedContent(messageWrapper, data, 2500, 'updated');

				if(typeof successCallback === 'function') {
					successCallback();
				}
			},
			error: function (data) {
				showUpdatedContent(messageWrapper, data, 2500, 'error');
			}
		});
	}, 500);

	var getSerializedSettings = function(form) {
		var disabled = form.find(':input:disabled').removeAttr('disabled'),
			settings = form.find('input, select, textarea').serialize();

		disabled.attr('disabled','disabled');

		return settings;
	};

	var showSpinner = function(wrapper) {
		$('.js-wpml-ls-messages').removeClass('success error').hide().empty();
		wrapper.siblings('.spinner').addClass('is-active');
	};

	var showUpdatedContent = function(wrapper, content, delay, type) {
		wrapper.siblings('.spinner').removeClass('is-active');

		wrapper.removeClass('updated notice error');

		if(type) {
			wrapper.addClass(type);
		}

		wrapper.html(content).fadeIn();

		if(delay) {
			wrapper.delay(delay).fadeOut();
		}

		$('.js-wpml-ls-dialog-save').prop('disabled', false);
	};

	var updateDialogInlineStyle = function (styles) {
		 $('#' + dialogInlineStyleId).remove();

		if(styles) {
			var newDialogStyle;

			if (styles instanceof jQuery) {
				newDialogStyle = styles;
			} else {
				newDialogStyle = $($.parseHTML(styles)).first();
			}

			newDialogStyle.attr('id', dialogInlineStyleId);
			$('#' + additionalCssStyleId).before(newDialogStyle);
		}
	};

	var copyDialogInlineStyleToSlot = function (itemType, slug) {
		var dialogStyleClone = $('#' + dialogInlineStyleId).clone(),
			targetId         = 'wpml-ls-inline-styles-' + itemType + '-' + slug,
			targetStyle      = $('#' + targetId);

		dialogStyleClone.attr('id', targetId);

		if (targetStyle.length) {
			targetStyle.replaceWith(dialogStyleClone);
		} else {
			$('#' + additionalCssStyleId).before(dialogStyleClone);
		}
	};

	var buildCSSLinks = function (css) {
		var i,
			linkTag;

		if (typeof css !== typeof undefined && null !== css) {
			for (i = 0; i < css.length; i++) {
				linkTag = $('link[href="' + css[i] + '"]');

				if (0 === linkTag.length) {
					linkTag = $('<link>');
					linkTag.attr('rel', 'stylesheet');
					linkTag.attr('type', 'text/css');
					linkTag.attr('media', 'all');
					linkTag.attr('href', css[i]);
					linkTag.prependTo('head');
				}
			}
		}
	};

	var buildJSScripts = function (js) {
		var i,
			jsTag;

		if (typeof js !== typeof undefined && null !== js) {
			for (i = 0; i < js.length; i++) {
				jsTag = $('script[src="' + js[i] + '"]');

				if (0 === jsTag.length) {
					jsTag = $('');
					jsTag.attr('type', 'text/javascript');
					jsTag.attr('src', js[i]);
					jsTag.prependTo('head');
				}
			}
		}
	};

	return {
		'init': init
	};

})( jQuery, wpml_language_switcher_admin );

jQuery(document).ready(function () {
	"use strict";

	WPML_core.languageSwitcher.init();
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. K. Ned. Akad. Wet. 74(1): 39 (1971)

#### Original name
Polyporus chrysoloma Fr., 1861

### Remarks
null


text:
<?php

use qeti\SimplePOData\BaseQueryProvider;

class QueryProvider extends BaseQueryProvider
{
    public function __construct(\PDO $db){
        parent::__construct($db);
    }

    /**
     * Get associated array with rows
     * @param string $sql SQL query
     * @param array $parameters Parameters for SQL query
     * @return mixed[]|null
     */
    protected function queryAll($sql, $parameters = null)
    {
        $statement = $this->db->prepare($sql);
        $statement->execute($parameters);
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get one value
     * @param string $sql SQL query
     * @param array $parameters Parameters for SQL query
     * @return mixed|null
     */
    protected function queryScalar($sql, $parameters = null)
    {
        $statement = $this->db->prepare($sql);
        $statement->execute($parameters);
        $data = $statement->fetchAll(PDO::FETCH_COLUMN);
        if ($data) {
            return $data[0];
        }
        return null;
    }

    /**
     * Execute query
     * @param string $sql SQL query
     * @param array $parameters Parameters for SQL query
     * @return mixed|null
     */
    protected function execute($sql, $parameters = null)
    {
        $statement = $this->db->prepare($sql);
        return $statement->execute($parameters);
    }

}