text:
function [x,fval,exitflag,output]=fminsearchbnd(fun,x0,LB,UB,options,varargin)
% FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation
% usage: x=FMINSEARCHBND(fun,x0)
% usage: x=FMINSEARCHBND(fun,x0,LB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...)
% usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...)
%
% arguments:
%  fun, x0, options - see the help for FMINSEARCH
%
%  LB - lower bound vector or array, must be the same size as x0
%
%       If no lower bounds exist for one of the variables, then
%       supply -inf for that variable.
%
%       If no lower bounds at all, then LB may be left empty.
%
%       Variables may be fixed in value by setting the corresponding
%       lower and upper bounds to exactly the same value.
%
%  UB - upper bound vector or array, must be the same size as x0
%
%       If no upper bounds exist for one of the variables, then
%       supply +inf for that variable.
%
%       If no upper bounds at all, then UB may be left empty.
%
%       Variables may be fixed in value by setting the corresponding
%       lower and upper bounds to exactly the same value.
%
% Notes:
%
%  If options is supplied, then TolX will apply to the transformed
%  variables. All other FMINSEARCH parameters should be unaffected.
%
%  Variables which are constrained by both a lower and an upper
%  bound will use a sin transformation. Those constrained by
%  only a lower or an upper bound will use a quadratic
%  transformation, and unconstrained variables will be left alone.
%
%  Variables may be fixed by setting their respective bounds equal.
%  In this case, the problem will be reduced in size for FMINSEARCH.
%
%  The bounds are inclusive inequalities, which admit the
%  boundary values themselves, but will not permit ANY function
%  evaluations outside the bounds. These constraints are strictly
%  followed.
%
%  If your problem has an EXCLUSIVE (strict) constraint which will
%  not admit evaluation at the bound itself, then you must provide
%  a slightly offset bound. An example of this is a function which
%  contains the log of one of its parameters. If you constrain the
%  variable to have a lower bound of zero, then FMINSEARCHBND may
%  try to evaluate the function exactly at zero.
%
%
% Example usage:
% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
%
% fminsearch(rosen,[3 3])     % unconstrained
% ans =
%    1.0000    1.0000
%
% fminsearchbnd(rosen,[3 3],[2 2],[])     % constrained
% ans =
%    2.0000    4.0000
%
% See test_main.m for other examples of use.
%
%
% See also: fminsearch, fminspleas
%
%
% Author: John D'Errico
% E-mail: woodchips@rochester.rr.com
% Release: 4
% Release date: 7/23/06

% size checks
xsize = size(x0);
x0 = x0(:);
n=length(x0);

if (nargin<3) || isempty(LB)
  LB = repmat(-inf,n,1);
else
  LB = LB(:);
end
if (nargin<4) || isempty(UB)
  UB = repmat(inf,n,1);
else
  UB = UB(:);
end

if (n~=length(LB)) || (n~=length(UB))
  error 'x0 is incompatible in size with either LB or UB.'
end

% set default options if necessary
if (nargin<5) || isempty(options)
  options = optimset('fminsearch');
end

% stuff into a struct to pass around
params.args = varargin;
params.LB = LB;
params.UB = UB;
params.fun = fun;
params.n = n;

% 0 --> unconstrained variable
% 1 --> lower bound only
% 2 --> upper bound only
% 3 --> dual finite bounds
% 4 --> fixed variable
params.BoundClass = zeros(n,1);
for i=1:n
  k = isfinite(LB(i)) + 2*isfinite(UB(i));
  params.BoundClass(i) = k;
  if (k==3) && (LB(i)==UB(i))
    params.BoundClass(i) = 4;
  end
end

% transform starting values into their unconstrained
% surrogates. Check for infeasible starting guesses.
x0u = x0;
k=1;
for i = 1:n
  switch params.BoundClass(i)
    case 1
      % lower bound only
      if x0(i)<=LB(i)
        % infeasible starting value. Use bound.
        x0u(k) = 0;
      else
        x0u(k) = sqrt(x0(i) - LB(i));
      end

      % increment k
      k=k+1;
    case 2
      % upper bound only
      if x0(i)>=UB(i)
        % infeasible starting value. use bound.
        x0u(k) = 0;
      else
        x0u(k) = sqrt(UB(i) - x0(i));
      end

      % increment k
      k=k+1;
    case 3
      % lower and upper bounds
      if x0(i)<=LB(i)
        % infeasible starting value
        x0u(k) = -pi/2;
      elseif x0(i)>=UB(i)
        % infeasible starting value
        x0u(k) = pi/2;
      else
        x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1;
        % shift by 2*pi to avoid problems at zero in fminsearch
        % otherwise, the initial simplex is vanishingly small
        x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k))));
      end

      % increment k
      k=k+1;
    case 0
      % unconstrained variable. x0u(i) is set.
      x0u(k) = x0(i);

      % increment k
      k=k+1;
    case 4
      % fixed variable. drop it before fminsearch sees it.
      % k is not incremented for this variable.
  end

end
% if any of the unknowns were fixed, then we need to shorten
% x0u now.
if k<=n
  x0u(k:n) = [];
end

% were all the variables fixed?
if isempty(x0u)
  % All variables were fixed. quit immediately, setting the
  % appropriate parameters, then return.

  % undo the variable transformations into the original space
  x = xtransform(x0u,params);

  % final reshape
  x = reshape(x,xsize);

  % stuff fval with the final value
  fval = feval(params.fun,x,params.args{:});

  % fminsearchbnd was not called
  exitflag = 0;

  output.iterations = 0;
  output.funcount = 1;
  output.algorithm = 'fminsearch';
  output.message = 'All variables were held fixed by the applied bounds';

  % return with no call at all to fminsearch
  return
end

% now we can call fminsearch, but with our own
% intra-objective function.
[xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params);

% undo the variable transformations into the original space
x = xtransform(xu,params);

% final reshape
x = reshape(x,xsize);

% ======================================
% ========= begin subfunctions =========
% ======================================
function fval = intrafun(x,params)
% transform variables, then call original function

% transform
xtrans = xtransform(x,params);

% and call fun
fval = feval(params.fun,xtrans,params.args{:});

% ======================================
function xtrans = xtransform(x,params)
% converts unconstrained variables into their original domains

xtrans = zeros(1,params.n);
% k allows some variables to be fixed, thus dropped from the
% optimization.
k=1;
for i = 1:params.n
  switch params.BoundClass(i)
    case 1
      % lower bound only
      xtrans(i) = params.LB(i) + x(k).^2;

      k=k+1;
    case 2
      % upper bound only
      xtrans(i) = params.UB(i) - x(k).^2;

      k=k+1;
    case 3
      % lower and upper bounds
      xtrans(i) = (sin(x(k))+1)/2;
      xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i);
      % just in case of any floating point problems
      xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i)));

      k=k+1;
    case 4
      % fixed variable, bounds are equal, set it at either bound
      xtrans(i) = params.LB(i);
    case 0
      % unconstrained variable.
      xtrans(i) = x(k);

      k=k+1;
  end
end


text:
export const API_BASE_URL = 'http://localhost:3001';

export const API_REQUEST = Symbol('API_REQUEST');

redpajama_set_name: RedPajamaGithub


text:
package com.ignissoft.avalanche.ffu;

import com.ignissoft.avalanche.AvlAttributesInterface;
import com.ignissoft.avalanche.AvlCluster;
import com.ignissoft.avalanche.AvlObject;

public class AvRouterSet extends AvlObject {

	public static enum AvRouterSetAttributes implements AvlAttributesInterface {
		router;

		@Override
		public String attributeName() {
			return name();
		}

	}

	public AvRouterSet(AvlCluster cluster, String handle) throws Exception {
		super("routerSet", cluster, handle);
		String routers = getProperty(AvRouterSetAttributes.router);
		if (!routers.equals("")) {
			for (String routerHandle : routers.split(" ")) {
				AvRouter router = new AvRouter(this, routerHandle);
				cluster.getObjects().put(router.getName(), router);
			}
		}
	}

	/*
	 * Standard Getters and Setters
	 */

}


text:
class SpriteFrameSelection;
class editor: public State
{
public:
	editor(clan::DisplayWindow &display_window);
	~editor();

	bool init();
	bool run();
	bool exit();

	bool pause();
	bool resume();

protected:
	///event funcs
	void on_input(const clan::InputEvent & e);
	void on_button_clicked(clan::PushButton * btn);
	void on_frame_select(clan::Rect frame);
	void on_layer_select(int32_t layer);
	void on_sprite_sheet_select(int32_t sprite_sheet);
	void on_spawn_select(int32_t spawn);
	bool on_close_wnd(clan::GUIComponent * wnd);
	void on_exit(bool confirm);

	///editor specific funcs
	void init_level();
	void init_gui();
	void init_gui_layer_dropbox(clan::Window * root, const clan::Rect pos);
	void init_gui_sprite_sheet_dropbox(clan::Window * root, const clan::Rect pos);
	void init_gui_spawn_dropbox(clan::Window * root, const clan::Rect pos);
	void init_gui_load_map_button(clan::Window * root, const clan::Rect pos);
	void init_gui_save_map_button(clan::Window * root, const clan::Rect pos);
	void update_gui_sprite_sheet_dropbox();
	void init_gui_axis_checkbox(clan::Window * root, int left, int right, clan::Size size);
	void edge_pan(const clan::vec2 & pos);
	void draw_world_axis(bool t, bool c, bool w);
	void draw_hover_box(bool draw);
	void draw_selection_box(const clan::Point & pos, bool draw);
	void change_tile_sprite(const clan::vec2 & pos, bool remove=false);
	bool editor::open_file(std::string & str);
	bool editor::save_file(std::string & str);

protected:
	bool m_run;

	///input event slots
	clan::Slot m_key_up;
	clan::Slot m_mouse_up;
	clan::Slot m_mouse_down;
	clan::Slot m_mouse_move;

	clan::ResourceManager	m_resources;
	clan::DisplayWindow		m_window;
	clan::Canvas			m_canvas;
	clan::GameTime			m_game_time;

	///Kameros poslinki
	clan::vec2 m_pos,
		m_pan,
		m_offset,
		m_scroll;

	///game
	TileMap m_tile_map;

	///gui
	clan::GUIManager				m_gui_manager;
	clan::GUIWindowManagerDirect	m_window_manager;
	YNDialogue						*m_save_window;

	///gui elements
	clan::GUIComponent			*m_gui_root;
	clan::PushButton			*m_button_multi_tile,
								*m_button_spawn,
								*m_button_sprite_frame,
								*m_button_select_resource_file,
								*m_button_load_map,
								*m_button_save_map;
	clan::ComboBox				*m_combo_layer,
								*m_combo_sprite_sheet,
								*m_combo_spawn;
	clan::PopupMenu				m_combo_menu_layer,
								m_combo_menu_sprite_sheet,
								m_combo_menu_spawn;
	clan::CheckBox				*m_checkbox_t,
								*m_checkbox_c,
								*m_checkbox_o;
	clan::Window				*m_sprite_selection_window,
								*m_editor_window;
	SpriteFrameSelection		*m_sprite_frame_selection;

	clan::Slot m_frame_select, m_save;
	int32_t m_selected_layer, m_selected_sprite_sheet, m_selected_spawn_type;
	SelectedSprites *m_selected_sprites;

};

#endif // EDITOR_H


text:
package org.sakaiproject.content.repository.tool.panels;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.content.repository.logic.ProjectLogic;
import org.sakaiproject.content.repository.logic.ProjectUtils;
import org.sakaiproject.content.repository.model.FormMode;
import org.sakaiproject.content.repository.model.LearningObject;
import org.sakaiproject.content.repository.model.TechnicalRequirement;
import org.sakaiproject.content.repository.tool.components.HashMapDropdown;
import org.sakaiproject.content.repository.tool.components.ListEditor;
import org.sakaiproject.content.repository.tool.components.ListItem;
import org.sakaiproject.content.repository.tool.components.RemoveButton;
import org.sakaiproject.content.repository.tool.pages.BrowsePage;
import org.sakaiproject.content.repository.tool.pages.SearchPage;

/**
 * Panel for the technical requirements tab. Allows multiples
 *
 * @author Steve Swinsburg (steve.swinsburg@gmail.com)
 *
 */
public class TabTechReqs extends Panel {

	@SpringBean(name="org.sakaiproject.content.repository.logic.ProjectLogic")
	private ProjectLogic logic;

	private final FormMode mode;
	private final ListEditor<TechnicalRequirement> editor;
	private LearningObject lo;

	public TabTechReqs(String id, LearningObject data, FormMode formMode) {
		super(id);
		this.mode=formMode;
		this.lo=data;

		//stub out at least one techreq if there are none, so the page has a form to begin with
		if(lo.getTechReqs().getTechReqs().isEmpty()) {
			//add a blank one so the page is stubbed
			lo.getTechReqs().getTechReqs().add(new TechnicalRequirement());
		}

		Form form = new Form("form") {
			@Override
			protected void onSubmit() {

				if(mode == FormMode.ADD) {
					boolean result = logic.addNewLearningObject(lo);
					if(result) {
						info(new StringResourceModel("success.lo.created", this, null).getString());
						setResponsePage(new BrowsePage());
					} else {
						error(new StringResourceModel("error.failed.add", this, null).getString());
					}
				}

				if(mode == FormMode.EDIT) {
					boolean result = logic.updateLearningObject(lo);
					if(result) {
						info(new StringResourceModel("success.lo.updated", this, null).getString());
						setResponsePage(new BrowsePage());
					} else {
						error(new StringResourceModel("error.failed.update", this, null).getString());
					}
				}

				if(mode == FormMode.SEARCH) {
					System.out.println("Performing advanced search");

					String searchString = logic.getAdvancedSearchString(lo);

					setResponsePage(new SearchPage(searchString));
				}

			}
		};
		add(form);

		Label instructions = new Label("instructions", new ResourceModel("instruction.lo.techreqs.1"));
		instructions.setVisible(mode != FormMode.SEARCH);
		form.add(instructions);

		editor = new ListEditor<TechnicalRequirement>("techReqs", new PropertyModel(this, "lo.techReqs.techReqs")) {
			@Override
			protected void onPopulateItem(ListItem<TechnicalRequirement> item) {
				item.setModel(new CompoundPropertyModel(item.getModel()));
				item.add(new HashMapDropdown("techReqType", ProjectUtils.getLabelledDropdownMap("dropdown.tech_req_type")));
				item.add(new TextField("techReqName"));
				item.add(new TextField("techReqMinVersion"));
				item.add(new TextField("techReqMaxVersion"));
				item.add(new HashMapDropdown("techReqAndOr", ProjectUtils.getLabelledDropdownMap("dropdown.andor")));
				item.add(new TextArea("techReqInstallRemarks"));
				item.add(new TextArea("techReqOther"));

				RemoveButton r = new RemoveButton("remove");
				r.setVisible(mode != FormMode.SEARCH);
				item.add(r);
			}
		};

		//add button
		form.add(new Button("add") {
			@Override
			public void onSubmit() {
				editor.addItem(new TechnicalRequirement());
			}

			@Override
			public boolean isVisible() {
				//do not display for searching
				return (mode != FormMode.SEARCH);
			}

		}.setDefaultFormProcessing(false));

		form.add(editor);

	}

}


text:
package cpu

import (
	"encoding/json"
	"runtime"
	"strconv"
	"strings"

	"github.com/shirou/gopsutil/internal/common"
)

type TimesStat struct {
	CPU       string  `json:"cpu"`
	User      float64 `json:"user"`
	System    float64 `json:"system"`
	Idle      float64 `json:"idle"`
	Nice      float64 `json:"nice"`
	Iowait    float64 `json:"iowait"`
	Irq       float64 `json:"irq"`
	Softirq   float64 `json:"softirq"`
	Steal     float64 `json:"steal"`
	Guest     float64 `json:"guest"`
	GuestNice float64 `json:"guestNice"`
	Stolen    float64 `json:"stolen"`
}

type InfoStat struct {
	CPU        int32    `json:"cpu"`
	VendorID   string   `json:"vendorId"`
	Family     string   `json:"family"`
	Model      string   `json:"model"`
	Stepping   int32    `json:"stepping"`
	PhysicalID string   `json:"physicalId"`
	CoreID     string   `json:"coreId"`
	Cores      int32    `json:"cores"`
	ModelName  string   `json:"modelName"`
	Mhz        float64  `json:"mhz"`
	CacheSize  int32    `json:"cacheSize"`
	Flags      []string `json:"flags"`
}

var invoke common.Invoker

func init() {
	invoke = common.Invoke{}
}

var lastCPUTimes []TimesStat
var lastPerCPUTimes []TimesStat

func Counts(logical bool) (int, error) {
	return runtime.NumCPU(), nil
}

func (c TimesStat) String() string {
	v := []string{
		`"cpu":"` + c.CPU + `"`,
		`"user":` + strconv.FormatFloat(c.User, 'f', 1, 64),
		`"system":` + strconv.FormatFloat(c.System, 'f', 1, 64),
		`"idle":` + strconv.FormatFloat(c.Idle, 'f', 1, 64),
		`"nice":` + strconv.FormatFloat(c.Nice, 'f', 1, 64),
		`"iowait":` + strconv.FormatFloat(c.Iowait, 'f', 1, 64),
		`"irq":` + strconv.FormatFloat(c.Irq, 'f', 1, 64),
		`"softirq":` + strconv.FormatFloat(c.Softirq, 'f', 1, 64),
		`"steal":` + strconv.FormatFloat(c.Steal, 'f', 1, 64),
		`"guest":` + strconv.FormatFloat(c.Guest, 'f', 1, 64),
		`"guestNice":` + strconv.FormatFloat(c.GuestNice, 'f', 1, 64),
		`"stolen":` + strconv.FormatFloat(c.Stolen, 'f', 1, 64),
	}

	return `{` + strings.Join(v, ",") + `}`
}

// Total returns the total number of seconds in a CPUTimesStat
func (c TimesStat) Total() float64 {
	total := c.User + c.System + c.Nice + c.Iowait + c.Irq + c.Softirq + c.Steal +
		c.Guest + c.GuestNice + c.Idle + c.Stolen
	return total
}

func (c InfoStat) String() string {
	s, _ := json.Marshal(c)
	return string(s)
}


text:
published: true
layout: post
title: <76> window batch script
tags:
  - Test
image:
  feature: abstract-8mod.jpg
---
Need a method to quickly insert some windows batch scripts to run my `hexo generate & hexo serve --draft` function really quickly followed by `hexo deploy`


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.P597.html">

Redirecting to type.P597.html...


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>toggleStyleWithClassList </title>

Article 1

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptatibus earum asperiores recusandae harum sunt, id nisi nemo possimus voluptate architecto molestiae incidunt, eos magni, nostrum blanditiis iusto sapiente officiis assumenda.

Article 2

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptatibus earum asperiores recusandae harum sunt, id nisi nemo possimus voluptate architecto molestiae incidunt, eos magni, nostrum blanditiis iusto sapiente officiis assumenda.

Article 3

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptatibus earum asperiores recusandae harum sunt, id nisi nemo possimus voluptate architecto molestiae incidunt, eos magni, nostrum blanditiis iusto sapiente officiis assumenda.


text:
package com.amazon.ask.colorpicker.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Intent;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.Request;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.Slot;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

import static com.amazon.ask.colorpicker.handlers.WhatsMyColorIntentHandler.COLOR_KEY;
import static com.amazon.ask.colorpicker.handlers.WhatsMyColorIntentHandler.COLOR_SLOT;
import static com.amazon.ask.request.Predicates.intentName;

public class MyColorIsIntentHandler implements RequestHandler {
    @Override
    public boolean canHandle(HandlerInput input) {
        return input.matches(intentName("MyColorIsIntent"));
    }

    @Override
    public Optional<Response> handle(HandlerInput input) {
        Request request = input.getRequestEnvelope().getRequest();
        IntentRequest intentRequest = (IntentRequest) request;
        Intent intent = intentRequest.getIntent();
        Map<String, Slot> slots = intent.getSlots();

        // Get the color slot from user input.
        Slot favoriteColorSlot = slots.get(COLOR_SLOT);
        String speechText, repromptText;

        // Check for favorite color and create output to user.
        if(favoriteColorSlot != null
            && favoriteColorSlot.getResolutions() != null
            && favoriteColorSlot.getResolutions().toString().contains("ER_SUCCESS_MATCH")) {
            // Store the user's favorite color in the Session and create response.
            String favoriteColor = favoriteColorSlot.getValue();
            input.getAttributesManager().setSessionAttributes(Collections.singletonMap(COLOR_KEY, favoriteColor));

            speechText =
                    String.format("I now know that your favorite color is %s. You can ask me your "
                            + "favorite color by saying, what's my favorite color?", favoriteColor);
            repromptText =
                    "You can ask me your favorite color by saying, what's my favorite color?";

        } else {
            // Render an error since user input is out of list of color defined in interaction model.
            speechText = "Please provide a valid color, your options are green, blue, purple, red, orange and yellow. " +
                    "Please try again.";
            repromptText =
                    "I'm not sure what your favorite color is. You can tell me your favorite "
                            + "color by saying, my color is red.";
        }

        return input.getResponseBuilder()
                .withSimpleCard("ColorSession", speechText)
                .withSpeech(speechText)
                .withReprompt(repromptText)
                .withShouldEndSession(false)
                .build();
    }

}


text:
create table tab_new
(
  id number(15),
  constraint tab_new_pk1 primary key (id)
);


text:
'use strict';
import type {RelayMockEnvironment} from '../../relay-test-utils/RelayModernMockEnvironment';
import type {OperationDescriptor} from 'relay-runtime/store/RelayStoreTypes';

const ReactRelayQueryRenderer = require('../ReactRelayQueryRenderer');
const React = require('react');
const {useEffect} = require('react');
const ReactTestRenderer = require('react-test-renderer');
const {
  Observable,
  createOperationDescriptor,
  graphql,
} = require('relay-runtime');
const {createMockEnvironment} = require('relay-test-utils');

function expectToHaveFetched(
  environment: RelayMockEnvironment,
  query: OperationDescriptor,
  {count}: {count: number},
) {
  // $FlowFixMe[method-unbinding] added when improving typing for this parameters
  expect(environment.execute).toBeCalledTimes(count);
  // $FlowFixMe[method-unbinding] added when improving typing for this parameters
  expect(environment.execute.mock.calls[0][0].operation).toMatchObject({
    fragment: expect.anything(),
    request: {
      node: query.request.node,
      variables: query.request.variables,
    },
    root: expect.anything(),
  });
  expect(
    environment.mock.isLoading(query.request.node, query.request.variables, {
      force: true,
    }),
  ).toEqual(true);
}

// TODO(T83890478): enable once double invoked effects lands in xplat
describe.skip('ReactRelayQueryRenderer-react-double-effects', () => {
  let environment;
  let gqlQuery;
  let query;
  let variables;
  let release;
  let cancelNetworkRequest;

  beforeEach(() => {
    jest.spyOn(console, 'warn').mockImplementationOnce(() => {});

    environment = createMockEnvironment();
    release = jest.fn();
    // $FlowFixMe[method-unbinding] added when improving typing for this parameters
    const originalRetain = environment.retain;
    (environment: $FlowFixMe).retain = jest.fn(operation => {
      const originalDisposable = originalRetain(operation);
      return {
        dispose() {
          release();
          return originalDisposable.dispose();
        },
      };
    });

    cancelNetworkRequest = jest.fn();
    // $FlowFixMe[method-unbinding] added when improving typing for this parameters
    const originalExecute = environment.execute;
    (environment: $FlowFixMe).execute = jest.fn((...args) => {
      const originalObservable = originalExecute(...args);

      return Observable.create(sink => {
        const sub = originalObservable.subscribe(sink);
        return () => {
          cancelNetworkRequest();
          sub.unsubscribe();
        };
      });
    });

    gqlQuery = graphql`
      query ReactRelayQueryRendererReactDoubleEffectsTestUserQuery($id: ID!) {
        node(id: $id) {
          id
          ... on User {
            name
          }
        }
      }
    `;

    variables = {id: '1'};
    query = createOperationDescriptor(gqlQuery, variables, {force: true});
  });

  afterEach(() => {
    environment.mockClear();
    jest.clearAllTimers();
  });

  it('forces a re-render and refetches query when effects are double invoked', () => {
    let renderLogs = [];
    const QueryComponent = function ({node}: {node: any}) {
      const name = node?.name ?? 'Empty';
      useEffect(() => {
        renderLogs.push(`commit: ${name}`);
        return () => {
          renderLogs.push(`cleanup: ${name}`);
        };
      }, [name]);

      renderLogs.push(`render: ${name}`);
      return name;
    };

    const QueryContainer = function (props: {variables: {id: string}}) {
      return (
        <ReactRelayQueryRenderer
          cacheConfig={{force: true}}
          environment={environment}
          query={gqlQuery}
          render={({props: renderProps}) => {
            if (!renderProps) {
              return 'Fallback';
            }
            return <QueryComponent node={renderProps.node} />;
          }}
          variables={props.variables}
        />
      );
    };

    let instance;
    ReactTestRenderer.act(() => {
      instance = ReactTestRenderer.create(
        // Using StrictMode will trigger double invoke effect behavior
        <React.StrictMode>
          <QueryContainer variables={variables} />
        </React.StrictMode>,
        // $FlowFixMe
        {unstable_isConcurrent: true, unstable_strictMode: true},
      );
    });
    if (!instance) {
      throw new Error('Failed to render during test.');
    }

    // After the component mounts, React double invoke effects will
    // be triggered, simulating what would happen if the component was
    // hidden and re-shown:

    // The effect cleanup will execute, so we assert that
    // the query is disposed:
    expect(release).toHaveBeenCalledTimes(1);
    // And that the request is cancelled
    expect(cancelNetworkRequest).toHaveBeenCalledTimes(1);

    // The component will be "reconstructed", so we assert
    // that a second network request is started
    expectToHaveFetched(environment, query, {count: 2});

    // Assert that query is permanentently retained
    // $FlowFixMe[method-unbinding] added when improving typing for this parameters
    expect(environment.retain).toHaveBeenCalledTimes(2);

    // Assert the loading state while the query is loading
    expect(renderLogs).toEqual([]);
    expect(instance.toJSON()).toEqual('Fallback');

    // Resolve network response
    // $FlowFixMe[method-unbinding] added when improving typing for this parameters
    environment.execute.mockClear();
    ReactTestRenderer.act(() => {
      environment.mock.resolve(gqlQuery, {
        data: {
          node: {
            __typename: 'User',
            id: variables.id,
            name: 'Alice 1',
            username: 'Alice',
          },
        },
      });
      jest.runAllImmediates();
    });

    expect(instance.toJSON()).toEqual('Alice 1');
    expect(renderLogs).toEqual([
      'render: Alice 1',
      'commit: Alice 1',
      'cleanup: Alice 1',
      'commit: Alice 1',
    ]);

    // Assert component is properly subscribed to the data.
    renderLogs = [];
    ReactTestRenderer.act(() => {
      environment.commitPayload(query, {
        node: {
          __typename: 'User',
          id: variables.id,
          name: 'Alice 2',
          username: 'Alice',
        },
      });
    });

    expect(instance.toJSON()).toEqual('Alice 2');
    expect(renderLogs).toEqual([
      'render: Alice 2',
      'cleanup: Alice 1',
      'commit: Alice 2',
    ]);
  });
});


text:
def serving_size_calc(item_to_make, ingredients_num) #takes an item to make and number of ingredients as inputs
  library = {"cookie" => 1, "cake" =>  5, "pie" => 7}
  # error_counter = 3

  # library.each do |food| # if the item to make is not in the library then this will increase the error counter
  #   if library[food] != library[item_to_make]
  #     error_counter += -1
  #   end
  # end
  if library.has_key?(item_to_make)
    serving_size = library[item_to_make]
    remaining_ingredients = ingredients_num % serving_size
    else
      raise ArgumentError.new("#{item_to_make} is not a valid input, try 'cookie', 'cake' or 'pie.'")
  end

 # if error_counter > 0 # if the error counter is above 0 then raise arg error.
  #   raise ArgumentError.new("#{item_to_make} is not a valid input")
  # end

  # serving_size = library.values_at(item_to_make)[0] # this is calculating how much of the items you can make with the passed number of ingredients.
  # remaining_ingredients = num_of_ingredients % serving_size

  if remaining_ingredients < 5 #adding code to suggest making something with ingredients
    make_new_thing = 1
    thing_to_make = "cookies"
    elsif remaining_ingredients.between?(5, 7)
    make_new_thing = 5
    thing_to_make = "cakes"
    else
    make_new_thing = 7
    thing_to_make = "pies"
  end

  case remaining_ingredients # this calculates whether the item is made and what the remainder of ingredients are. (suggested feature is what item the person can make with the leftover ingredients)
  when 0
    return "Calculations complete: Make #{ingredients_num / serving_size} of #{item_to_make}"
  else
    return "Calculations complete: Make #{ingredients_num / serving_size} of #{item_to_make}, you have #{remaining_ingredients} leftover ingredients. Why don't you make #{remaining_ingredients / make_new_thing} #{thing_to_make}"
  end
end

p serving_size_calc("pie", 40)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
#p serving_size_calc("THIS IS AN ERROR", 5)

# Release 1:
# the code is taking an item to make and number of ingredients
# and returning how many of the items you can make with the
# given number of ingredients, for example it takes 7 ingredients
# to make 1 pie, so if you pass pie in (meaning you wan tot make a pie) and you have 7 ingredients then that means you can make 1 pie.

# Release 2: (write comments in code blocks to explain what it's doing)

# Release 3:

# Priortizing new features and Refactoring. I think the raise arg
# error can be re done to something like if the item to make isn't
# included in the hash raise an arg error. I think some of the
# varable names can be redone, they are not clear.
# accessing the hash value is more straight forward than the
# values_at method the dev is using.

#  Reflection

# Q:  What did you learn about making code readable by working on this challenge?

# I learned that the simpler you can make your code the better, because
# someone else will be looking at it, not just you!

# Q:  Did you learn any new methods? What did you learn about them?

# I learned between? and has_key? - between? to check if a value is between 2 numbers
# and has_key? to check if a hash has a given key.

# Q:  What did you learn about accessing data in hashes?

# There are multiple ways to access data in a hash simpliest should win over others
# for example hash[key]

# Q:  What concepts were solidified when working through this challenge?

# Checking values in a hash, raising arg errors (needs to be capitalized :). Adding clear explanation for arg error is important.


text:
package com.ajjpj.macro.tree.expr;

import com.ajjpj.macro.tree.MExpressionTree;

/**
 * @author arno
 */
public interface MBinaryExpressionTree extends MExpressionTree {
    MExpressionTree getLeft();
    MExpressionTree getRight();
    BinaryOperator getOperator();
}


text:
package org.sisioh.aws4s.sqs.model

import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry
import org.sisioh.aws4s.PimpedType

object DeleteMessageBatchRequestEntryFactory {

  def create(): DeleteMessageBatchRequestEntry =
    new DeleteMessageBatchRequestEntry()

  def create(id: String, receiptHandle: String): DeleteMessageBatchRequestEntry =
    new DeleteMessageBatchRequestEntry(id, receiptHandle)

}

class RichDeleteMessageBatchRequestEntry(val underlying: DeleteMessageBatchRequestEntry)
    extends AnyVal
    with PimpedType[DeleteMessageBatchRequestEntry] {

  def idOpt: Option[String] = Option(underlying.getId)

  def idOpt_=(value: Option[String]): Unit =
    underlying.setId(value.orNull)

  def withIdOpt(value: Option[String]): DeleteMessageBatchRequestEntry =
    underlying.withId(value.orNull)

}


text:
$(document).ready(function() {
    var $form = $('#myForm');
    $form.submit(function(e) {
        e.preventDefault();
        var data = $form.serialize();
        data += '&isAjax=1';
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: data,
            dataType: 'json',
            success:
            function(data) {
                var $messageTable = $('#message');
                var $commentsContainer = $('.content');
                $form[0].reset();
                $(data['data']).appendTo($commentsContainer);
                $(data['message']).appendTo($messageTable);
            }
        });

    });
});


text:
namespace walrus_pod_controller{

Pod::Pod(ros::NodeHandle nh)
  : nh_(nh), next_state_update_(0), controller_state_period_(0.5),
    command_timeout_(0.5) {
  last_command_.mode = walrus_pod_controller::PodCommand::DISABLED;
}

bool Pod::init(hardware_interface::EffortJointInterface* hw, urdf::Model urdf) {
  std::string joint_name;

  nh_.param("command_timeout", command_timeout_, command_timeout_);

  if (!nh_.getParam("joint", joint_name)) {
    ROS_ERROR("No joint given (namespace: %s)", nh_.getNamespace().c_str());
    return false;
  }

  joint_ = hw->getHandle(joint_name);
  boost::shared_ptr<const urdf::Joint> joint_urdf =  urdf.getJoint(joint_name);
  if (!joint_urdf) {
    ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str());
    return false;
  }

  if (!pid_controller_.init(ros::NodeHandle(nh_, "pid")))
    return false;

  controller_state_publisher_.reset(new realtime_tools::RealtimePublisher<control_msgs::JointControllerState>(nh_, "state", 1));

  command_sub_ = nh_.subscribe<walrus_pod_controller::PodCommand>("command", 1, &Pod::setCommandCallback, this);
}

void Pod::setCommandCallback(const walrus_pod_controller::PodCommandConstPtr& command) {
  walrus_pod_controller::PodCommandStamped command_stamped;
  command_stamped.header.stamp = ros::Time::now();
  command_stamped.command = *command;
  command_buffer_.writeFromNonRT(command_stamped);
}

void Pod::starting(const ros::Time& time) {
  walrus_pod_controller::PodCommandStamped command;
  command.header.stamp = ros::Time(0);
  command.command.mode = walrus_pod_controller::PodCommand::HOLD_POSITION;
  command_buffer_.initRT(command);
}

void Pod::stopping(const ros::Time& time) {
  joint_.setCommand(0.0); // set joint effort to zero
}

void Pod::update(const ros::Time& time, const ros::Duration& period) {
  double current_position = joint_.getPosition();
  walrus_pod_controller::PodCommandStamped command_stamped = *(command_buffer_.readFromRT());

  const double dt = (time - command_stamped.header.stamp).toSec();
  double command_effort;
  double command_position;
  double error;

  walrus_pod_controller::PodCommand command = command_stamped.command;
  if (dt > command_timeout_) {
    // timeout
    command.mode = walrus_pod_controller::PodCommand::DISABLED;
  }

  if(command.mode == walrus_pod_controller::PodCommand::POSITION ||
     command.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {
    // switching to position mode so reset the pid controller
    if(last_command_.mode != walrus_pod_controller::PodCommand::POSITION &&
       last_command_.mode != walrus_pod_controller::PodCommand::HOLD_POSITION) {
      pid_controller_.reset();
    }

    if(command.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {
      // Hold the position that was held last time
      if(last_command_.mode == walrus_pod_controller::PodCommand::HOLD_POSITION) {
	command.set_point = last_command_.set_point;
      }
      else {
	command.set_point = current_position;
      }
    }

    command_position = filters::clamp(command.set_point, -M_PI, M_PI);
    error = angles::shortest_angular_distance(current_position, command_position);
    command_effort = pid_controller_.computeCommand(error, period);
  }
  else if(command.mode == walrus_pod_controller::PodCommand::EFFORT) {
    command_position = std::numeric_limits<double>::quiet_NaN();
    error = std::numeric_limits<double>::quiet_NaN();
    command_effort = command.set_point;
  }
  else { // disabled
    command_position = std::numeric_limits<double>::quiet_NaN();
    error = std::numeric_limits<double>::quiet_NaN();
    command_effort = 0.0;
  }
  last_command_ = command;
  joint_.setCommand(command_effort);

  // publish state
  if (time > next_state_update_) {
    if(controller_state_publisher_ && controller_state_publisher_->trylock()) {
      controller_state_publisher_->msg_.header.stamp = time;
      controller_state_publisher_->msg_.set_point = command_position;
      controller_state_publisher_->msg_.process_value = current_position;
      controller_state_publisher_->msg_.process_value_dot = joint_.getVelocity();
      controller_state_publisher_->msg_.error = error;
      controller_state_publisher_->msg_.time_step = period.toSec();
      controller_state_publisher_->msg_.command = command_effort;

      double dummy;
      pid_controller_.getGains(controller_state_publisher_->msg_.p,
			       controller_state_publisher_->msg_.i,
			       controller_state_publisher_->msg_.d,
			       controller_state_publisher_->msg_.i_clamp,
			       dummy);
      controller_state_publisher_->unlockAndPublish();
    }
    next_state_update_ = time + controller_state_period_;
  }
}

WalrusPodController::WalrusPodController()
{
}

bool WalrusPodController::init(hardware_interface::EffortJointInterface* hw,
				 ros::NodeHandle& root_nh,
				 ros::NodeHandle &controller_nh)
{
  urdf::Model urdf;
  if (!urdf.initParam("robot_description")) {
    ROS_ERROR("Failed to parse urdf file");
    return false;
  }

  front.reset(new Pod(ros::NodeHandle(controller_nh, "front")));
  if(!front->init(hw, urdf))
    return false;

  back.reset(new Pod(ros::NodeHandle(controller_nh, "back")));
  if(!back->init(hw, urdf))
    return false;

  return true;
}

void WalrusPodController::update(const ros::Time& time, const ros::Duration& period)
{
  front->update(time, period);
  back->update(time, period);
}

void WalrusPodController::starting(const ros::Time& time)
{
  front->starting(time);
  back->starting(time);
}

void WalrusPodController::stopping(const ros::Time& time)
{
  front->stopping(time);
  back->stopping(time);
}

} // namespace diff_pod_controller


text:
function Add-VSSSMMaintenanceWindowTaskTaskInvocationParameters {
    <#
    .SYNOPSIS
        Adds an AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters resource property to the template. The TaskInvocationParameters property type specifies the task execution parameters for a maintenance window task in AWS Systems Manager.

    .DESCRIPTION
        Adds an AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters resource property to the template.
The TaskInvocationParameters property type specifies the task execution parameters for a maintenance window task in AWS Systems Manager.

TaskInvocationParameters is a property of the AWS::SSM::MaintenanceWindowTask: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html property type.

    .LINK
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html

    .PARAMETER MaintenanceWindowRunCommandParameters
        The parameters for a RUN_COMMAND task type.

        Type: MaintenanceWindowRunCommandParameters
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowruncommandparameters
        UpdateType: Mutable

    .PARAMETER MaintenanceWindowAutomationParameters
        The parameters for an AUTOMATION task type.

        Type: MaintenanceWindowAutomationParameters
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowautomationparameters
        UpdateType: Mutable

    .PARAMETER MaintenanceWindowStepFunctionsParameters
        The parameters for a STEP_FUNCTIONS task type.

        Type: MaintenanceWindowStepFunctionsParameters
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowstepfunctionsparameters
        UpdateType: Mutable

    .PARAMETER MaintenanceWindowLambdaParameters
        The parameters for a LAMBDA task type.

        Type: MaintenanceWindowLambdaParameters
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowlambdaparameters
        UpdateType: Mutable

    .FUNCTIONALITY
        Vaporshell
    #>
    [OutputType('Vaporshell.Resource.SSM.MaintenanceWindowTask.TaskInvocationParameters')]
    [cmdletbinding()]
    Param
    (
        [parameter(Mandatory = $false)]
        $MaintenanceWindowRunCommandParameters,
        [parameter(Mandatory = $false)]
        $MaintenanceWindowAutomationParameters,
        [parameter(Mandatory = $false)]
        $MaintenanceWindowStepFunctionsParameters,
        [parameter(Mandatory = $false)]
        $MaintenanceWindowLambdaParameters
    )
    Begin {
        $obj = [PSCustomObject]@{}
        $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
    }
    Process {
        foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
            switch ($key) {
                Default {
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
                }
            }
        }
    }
    End {
        $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.SSM.MaintenanceWindowTask.TaskInvocationParameters'
        Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
    }
}


text:
#ifndef __STD_INCLUDES_HEADER
#define __STD_INCLUDES_HEADER

// ADTF header
#include <adtf_platform_inc.h>
#include <adtf_plugin_sdk.h>
using namespace adtf;

// AADC header
#include "aadc_structs.h"

#endif // __STD_INCLUDES_HEADER


text:
namespace wgt
{
TypeId GenericDefinitionHelper::typeId() const
{
	static TypeId id = TypeId::getType<GenericObject>();
	return id;
}

IClassDefinition* GenericDefinitionHelper::getDefinition(const ObjectHandle& object) const
{
	auto genericObject = object.getBase<GenericObject>();
	TF_ASSERT(genericObject != nullptr);
	return genericObject->getDefinition();
}
} // end namespace wgt


text:
package url

import (
	"fmt"
	"github.com/fabioxgn/go-bot"
	. "github.com/smartystreets/goconvey/convey"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestURL(t *testing.T) {
	cmd := &bot.PassiveCmd{}
	getExecuted := false
	getResult := ""

	ts := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			getExecuted = true
			fmt.Fprintln(w, getResult)
		}))

	url := ts.URL

	Convey("Given a text", t, func() {

		Reset(func() {
			getExecuted = false
			getResult = ""
		})

		Convey("If the text is not a URL", func() {
			cmd.Raw = "foo bar"
			title, err := urlTitle(cmd)

			So(getExecuted, ShouldBeFalse)
			So(err, ShouldBeNil)
			So(title, ShouldBeBlank)
		})

		Convey("If the url contains no title", func() {
			cmd.Raw = "foo " + url

			title, err := urlTitle(cmd)

			So(getExecuted, ShouldBeTrue)
			So(err, ShouldBeNil)
			So(title, ShouldBeBlank)
		})

		Convey("If the url contains a title", func() {
			getResult = "<title>Google</title>"
			cmd.Raw = fmt.Sprintf("foo %s bar", url)

			title, err := urlTitle(cmd)

			So(getExecuted, ShouldBeTrue)
			So(err, ShouldBeNil)
			So(title, ShouldEqual, "Google")
		})

		Convey("If the text is a https URL", func() {
			httpsURL := "https://google.com"

			extractedURL := extractURL(fmt.Sprintf("foo %s bar", httpsURL))

			So(extractedURL, ShouldEqual, httpsURL)
		})

		Convey("If title starts or ends with a new line", func() {
			getResult = "<title>\nGoogle\n</title>"
			cmd.Raw = url

			title, err := urlTitle(cmd)

			So(err, ShouldBeNil)
			So(title, ShouldEqual, "Google")
		})

		Convey("If an error occurs while fetching the url", func() {
			cmd.Raw = "127.0.0.1:0"

			_, err := urlTitle(cmd)

			So(err, ShouldNotBeNil)
		})

		Convey("if the url doesn't have a protocol", func() {
			noProtocolURL := "google.com"

			extractedURL := extractURL(fmt.Sprintf("foo %s bar", noProtocolURL))

			So(extractedURL, ShouldEqual, "http://google.com")
		})

		Convey("if the text has fewer than 4 characters", func() {
			So(extractURL("a.a"), ShouldEqual, "")
		})

		Convey("if the url is invalid", func() {
			So(extractURL(":googlecom"), ShouldEqual, "")
		})

	})
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Navigator</title>
    <script>
        //nombre del navegador
        //appCodeName
        console.log(navigator.appCodeName);

        //nombre oficial del navegador
        //appName
        console.log(navigator.appName);

        //la version de l navegador
        //appVersion
        console.log(navigator.appVersion);

        //idioma del navegador
        console.log(navigator.browserLanguage);

        //boolean que indica si las cookies estan habilitadas
        console.log(navigator.cookieEnabled)

        //si java esta habilitado
        console.log(navigator.javaEnabled());

        //plataforma en que esta en navegador
        console.log(navigator.platform);

        //array con la lista de plugins instalados en el navegador
        console.log(navigator.plugins);

        //nombre del producto
        console.log(navigator.product);

        //
        console.log(navigator.productSub);
        console.log(navigator.userProfile);

        function hasPlugin(name){
            name = name.toLowerCase();
            for (var i =0; i<navigator.plugins.length;i++){
                if(navigator.plugins[i].name.toLowerCase().indexOf(name)> -1){
                    return true;
                }
            }
            return false;
        }

        alert(hasPlugin("Flash"));
        alert(hasPlugin("QuickTime"));

    </script>
</head>
<body>

</body>
</html>