/*
    TiMidity++ -- MIDI to WAVE converter and player
    Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
    Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    mod2midi.c

    Mixer event -> MIDI event conversion
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifndef NO_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif

#include "timidity.h"
#include "common.h"
#include "instrum.h"
#include "playmidi.h"
#include "readmidi.h"
#include "tables.h"
#include "mod.h"
#include "output.h"
#include "controls.h"
#include "unimod.h"
#include "mod2midi.h"
#include "filter.h"
#include "math.h"
#include "freq.h"

/* Define this to show all the notes touched by a bending in the
 * user interface's trace view.  This is interesting but disabled
 * because it needs tons of CPU power (tens of voices are activated
 * but unaudible). */
/* #define TRACE_SLIDE_NOTES */

/* Define this to give a volume envelope to a MOD's notes. This
 * could sound wrong with a few MODs, but gives richer sound most
 * of the time. */
#define USE_ENVELOPE

#define SETMIDIEVENT(e, at, t, ch, pa, pb) \
    { /* printf("%d %d " #t " %d %d\n", at, ch, pa, pb); */ \
      (e).time = (at); (e).type = (t); \
      (e).channel = (uint8)(ch); (e).a = (uint8)(pa); (e).b = (uint8)(pb); }

#define MIDIEVENT(at, t, ch, pa, pb) \
    { MidiEvent event; SETMIDIEVENT(event, at, t, ch, pa, pb); \
      readmidi_add_event(&event); }

/*
		   Clock
   SampleRate := ----------
		   Period
 */

#define NTSC_CLOCK 3579545.25
#define NTSC_RATE ((int32)(NTSC_CLOCK/428))

#define PAL_CLOCK 3546894.6
#define PAL_RATE ((int32)(PAL_CLOCK/428))

#define MOD_ROOT_NOTE      36

/* The internal bending register is 21-bits wide and it is made like this:
 *  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
 * | | | | | | | | | | | | | | | | | | | | | |
 * |    8 bits     |    8 bits     |  5 bits |
 * |  note  shift  |   fine tune   |discarded|
 * '---------------'---------------'---------'
 *
 * The note shift is an `offset' field: 128 = keep this note.
 * To compute it, the values given to the pitch-wheel MIDI event are
 * multiplied by the sensitivity. We want to be able to express a full
 * 120 notes bending (8 bits for the note shift + 8 for the fine tune)
 * with 14-bit pitch-wheel event, so we want a sensitivity value that
 * forces the bottom 7 bits of the internal register to 0.  This value
 * is of course 128.
 */

#define WHEEL_SENSITIVITY 		(1 << 7)
#define WHEEL_VALUE(bend)		((bend) / WHEEL_SENSITIVITY + 0x2000)

typedef struct _ModVoice
  {
    int sample;			/* current sample ID */
    int noteon;			/* (-1 means OFF status) */
    int time;			/* time when note was activated */
    int period;			/* current frequency */
    int wheel;			/* current pitch wheel value */
    int pan;			/* current panning */
    int vol;			/* current volume */

    int32 noteson[4];		/* bit map for notes 0-127 */
  }
ModVoice;

static void mod_change_tempo (int32 at, int bpm);
static int period2note (int period, int *finetune);

static ModVoice ModV[MOD_NUM_VOICES];
static int at;

/******************** bitmap handling macros **********************************/

#define bitmapGet(map, n)	((map)[(n) >> 5] &  (1 << ((n) & 31)))
#define bitmapSet(map, n)	((map)[(n) >> 5] |= (1 << ((n) & 31)))
#define bitmapClear(map)	((map)[0] = (map)[1] = (map)[2] = (map)[3] = 0)

static char significantDigitsLessOne[256] = {
    -1,							/* 1 */
    0,							/* 2 */
    1, 1,						/* 4 */
    2, 2, 2, 2,						/* 8 */
    3, 3, 3, 3, 3, 3, 3, 3,				/* 16 */
    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,	/* 32 */

    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,	/* 64 */
    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,

    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,	/* 128 */
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,

    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,	/* 256 */
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
};

/******************************************************************************/

void
mod_change_tempo (int32 at, int bpm)
{
  int32 tempo;
  int c, a, b;

  tempo = 60000000 / bpm;
  c = (tempo & 0xff);
  a = ((tempo >> 8) & 0xff);
  b = ((tempo >> 16) & 0xff);
  MIDIEVENT (at, ME_TEMPO, c, b, a);
}

int
period2note (int period, int *finetune)
{
  static int period_table[121] =
  {
  /*  C     C#    D     D#    E     F     F#    G     G#    A     A#    B  */
     13696,12928,12192,11520,10848,10240, 9664, 9120, 8608, 8096, 7680, 7248,
      6848, 6464, 6096, 5760, 5424, 5120, 4832, 4560, 4304, 4048, 3840, 3624,
      3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2024, 1920, 1812,
      1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016,  960,  906,
       856,  808,  762,  720,  678,  640,  604,  570,  538,  508,  480,  453,
       428,  404,  381,  360,  339,  320,  302,  285,  269,  254,  240,  226,
       214,  202,  190,  180,  170,  160,  151,  143,  135,  127,  120,  113,
       107,  101,   95,   90,   85,   80,   75,   71,   67,   63,   60,   56,
	53,   50,   47,   45,   42,   40,   37,   35,   33,   31,   30,   28,
	27,   25,   24,   22,   21,   20,   19,   18,   17,   16,   15,   14,

	-100 /* just a guard */
  };

  int note;
  int l, r, m;

  if (period < 14 || period > 13696)
  {
    ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "BAD period %d\n", period);
    return -1;
  }

  /* bin search */
  l = 0;
  r = 120;
  while (l < r)
    {
      m = (l + r) / 2;
      if (period_table[m] >= period)
	l = m + 1;
      else
	r = m;
    }
  note = l - 1;

  /*
   * 112 >= note >= 0
   * period_table[note] >= period > period_table[note + 1]
   */

  if (period_table[note] == period)
    *finetune = 0;
  else {
    /* Pick the closest note even if it is higher than this one.
     * (e.g. 721 - 720 < 762 - 721 ----> pick 720)    */
    if (period - period_table[note + 1] < period_table[note] - period)
      note++;

    /* fine tune completion */
    *finetune = ((period_table[note] - period) << 8) /
		   (period_table[note] - period_table[note + 1]);

    *finetune <<= 5;
  }
  return note;
}

/********** Interface to mod.c */

void
Voice_SetVolume (UBYTE v, UWORD vol)
{
  if (v >= MOD_NUM_VOICES)
    return;

  /* MOD volume --> MIDI volume */
  vol >>= 1;
  /* if (vol < 0) vol = 0; *//* UNSIGNED! */
  if (vol > 127) vol = 127;

  if (ModV[v].vol != vol) {
    ModV[v].vol = vol;
    MIDIEVENT (at, ME_EXPRESSION, v, vol, 0);
  }
}

void
Voice_SetPeriod (UBYTE v, ULONG period)
{
  int new_noteon, bend;

  if (v >= MOD_NUM_VOICES)
    return;

  ModV[v].period = period;
  if (ModV[v].noteon < 0)
    return;

  new_noteon = period2note (ModV[v].period, &bend);
#ifndef TRACE_SLIDE_NOTES
  bend += (new_noteon - ModV[v].noteon) << 13;
  new_noteon = ModV[v].noteon;
#endif
  bend = WHEEL_VALUE(bend);

  if (ModV[v].noteon != new_noteon)
    {
      MIDIEVENT(at, ME_KEYPRESSURE, v, ModV[v].noteon, 1);

      if (new_noteon < 0)
        {
	  ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
			  "Strange period %d",
			  ModV[v].period);
	  return;
	}
      else if (!bitmapGet(ModV[v].noteson, new_noteon))
	{
	  MIDIEVENT(ModV[v].time, ME_NOTEON, v, new_noteon, 1);
	  bitmapSet(ModV[v].noteson, new_noteon);
	}

    }

  if (ModV[v].wheel != bend)
    {
      ModV[v].wheel = bend;
      MIDIEVENT (at, ME_PITCHWHEEL, v, bend & 0x7F, (bend >> 7) & 0x7F);
    }

  if (ModV[v].noteon != new_noteon)
    {
      MIDIEVENT(at, ME_KEYPRESSURE, v, new_noteon, 127);
      ModV[v].noteon = new_noteon;
    }

}

void
Voice_SetPanning (UBYTE v, ULONG pan)
{
  if (v >= MOD_NUM_VOICES)
    return;
  if (pan == PAN_SURROUND)
    pan = PAN_CENTER; /* :-( */

  if (pan != ModV[v].pan) {
    ModV[v].pan = pan;
    MIDIEVENT(at, ME_PAN, v, pan * 127 / PAN_RIGHT, 0);
  }
}

void
Voice_Play (UBYTE v, SAMPLE * s, ULONG start)
{
  int new_noteon, bend;
  if (v >= MOD_NUM_VOICES)
    return;

  if (ModV[v].noteon != -1)
    Voice_Stop (v);

  new_noteon = period2note (ModV[v].period, &bend);
  bend = WHEEL_VALUE(bend);
  if (new_noteon < 0) {
    ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
			  "Strange period %d",
			  ModV[v].period);
    return;
  }

  ModV[v].noteon = new_noteon;
  ModV[v].time = at;
  bitmapSet(ModV[v].noteson, new_noteon);

  if (ModV[v].sample != s->id)
    {
      ModV[v].sample = s->id;
      MIDIEVENT(at, ME_SET_PATCH, v, ModV[v].sample, 0);
    }

  if (start > 0)
    {
      int a, b;
      a = (start & 0xff);
      b = ((start >> 8) & 0xff);
      MIDIEVENT (at, ME_PATCH_OFFS, v, a, b);
    }

  if (ModV[v].wheel != bend)
    {
      ModV[v].wheel = bend;
      MIDIEVENT (at, ME_PITCHWHEEL, v, bend & 0x7F, (bend >> 7) & 0x7F);
    }

  MIDIEVENT (at, ME_NOTEON, v, ModV[v].noteon, 127);
}

void
Voice_Stop (UBYTE v)
{
  int32 j;
  int n;

  if (v >= MOD_NUM_VOICES)
    return;

  if (ModV[v].noteon == -1)
    return;

#define TURN_OFF_8(base, ofs) 						\
  while (j & (0xFFL << (ofs))) {					\
    n = ofs + significantDigitsLessOne[(unsigned char) (j >> (ofs))];	\
    MIDIEVENT (at, ME_NOTEOFF, v, (base) + n, 63);			\
    j ^= 1 << n;							\
  }

#define TURN_OFF_32(base)						\
  do {									\
    TURN_OFF_8((base), 24)						\
    TURN_OFF_8((base), 16)						\
    TURN_OFF_8((base), 8)						\
    TURN_OFF_8((base), 0)						\
  } while(0)

  if ((j = ModV[v].noteson[0]) != 0) TURN_OFF_32(0);
  if ((j = ModV[v].noteson[1]) != 0) TURN_OFF_32(32);
  if ((j = ModV[v].noteson[2]) != 0) TURN_OFF_32(64);
  if ((j = ModV[v].noteson[3]) != 0) TURN_OFF_32(96);
  bitmapClear(ModV[v].noteson);
  ModV[v].noteon = -1;
}

BOOL
Voice_Stopped (UBYTE v)
{
  return (v >= MOD_NUM_VOICES) || (ModV[v].noteon == -1);
}

void
Voice_TickDone ()
{
  at++;
}

void
Voice_NewTempo (UWORD bpm, UWORD sngspd)
{
  mod_change_tempo(at, bpm);
}

void
Voice_EndPlaying ()
{
  int v;

  at += 48 / (60.0/125.0);		/* 1 second */
  for(v = 0; v < MOD_NUM_VOICES; v++)
    MIDIEVENT(at, ME_ALL_NOTES_OFF, v, 0, 0);
}

void
Voice_StartPlaying ()
{
  int v;

  readmidi_set_track(0, 1);

  current_file_info->divisions = 24;

  for(v = 0; v < MOD_NUM_VOICES; v++)
    {
	ModV[v].sample = -1;
	ModV[v].noteon = -1;
	ModV[v].time = -1;
	ModV[v].period = 0;
	ModV[v].wheel = 0x2000;
	ModV[v].vol = 127;
	ModV[v].pan = (v & 1) ? 127 : 0;
	bitmapClear(ModV[v].noteson);

	MIDIEVENT(0, ME_PAN, v, ModV[v].pan, 0);
        MIDIEVENT(0, ME_SET_PATCH, v, 1, 0);
        MIDIEVENT(0, ME_MAINVOLUME, v, 127, 0);
        MIDIEVENT(0, ME_EXPRESSION, v, 127, 0);
	/* MIDIEVENT(0, ME_MONO, v, 0, 0); */
	MIDIEVENT(0, ME_RPN_LSB, v, 0, 0);
	MIDIEVENT(0, ME_RPN_MSB, v, 0, 0);
	MIDIEVENT(0, ME_DATA_ENTRY_MSB, v, WHEEL_SENSITIVITY, 0);
	MIDIEVENT(0, ME_DRUMPART, v, 0, 0);
    }

  at = 1;
}

/* convert from 8bit value to fractional offset (15.15) */
static int32 env_offset(int offset)
{
    return (int32)offset << (7+15);
}

/* calculate ramp rate in fractional unit;
 * diff = 8bit, time = msec
 */
static int32 env_rate(int diff, double msec)
{
    double rate;

    if(msec < 6)
	msec = 6;
    if(diff == 0)
	diff = 255;
    diff <<= (7+15);
    rate = ((double)diff / play_mode->rate) * control_ratio * 1000.0 / msec;
    if(fast_decay)
	rate *= 2;
    return (int32)rate;
}

void shrink_huge_sample (Sample *sp)
{
    sample_t *orig_data;
    sample_t *new_data;
    unsigned int rate, new_rate;
    uint32 data_length, new_data_length;
    double loop_start, loop_end;
    double scale, scale2;
    double x, xfrac;
    double y;
    sample_t y1, y2, y3, y4;
    uint32 i, xtrunc;

    data_length = sp->data_length;
    if (data_length < (1 << FRACTION_BITS) - 1)
	return;
    loop_start = sp->loop_start;
    loop_end = sp->loop_end;
    rate = sp->sample_rate;

    scale = ((1 << (31 - FRACTION_BITS)) - 2.0) / data_length;
    new_rate = rate * scale;
    scale = new_rate / (float) rate;
    scale2 = (float) rate / new_rate;

    new_data_length = data_length * scale;
    loop_start *= scale;
    loop_end *= scale;

    ctl->cmsg(CMSG_INFO, VERB_NORMAL,
        "Sample too large (%ld): resampling down to %ld samples",
        data_length, new_data_length);

    orig_data = sp->data;
    new_data = calloc(new_data_length + 1, sizeof(sample_t));

    new_data[0] = orig_data[0];
    for (i = 1; i < new_data_length; i++)
    {
	x = i * scale2;
	xtrunc = (uint32) x;
	xfrac = x - xtrunc;

	if (xtrunc >= data_length - 1)
	{
	    if (xtrunc == data_length)
	    	new_data[i] = orig_data[data_length];
	    else	/* linear interpolation */
	    {
	        y2 = orig_data[data_length - 1];
	        y3 = orig_data[data_length];
	        new_data[i] = ceil((y2 + (y3 - y2) * xfrac) - 0.5);
	    }
	}
	else		/* cspline interpolation */
	{
	    y1 = orig_data[xtrunc - 1];
	    y2 = orig_data[xtrunc];
	    y3 = orig_data[xtrunc + 1];
	    y4 = orig_data[xtrunc + 2];

	    y = (6*y3 + (5*y4 - 11*y3 + 7*y2 - y1) *
		0.25 * (xfrac+1) * (xfrac-1)) * xfrac;
	    y = (((6*y2 + (5*y1 - 11*y2 + 7*y3 - y4) *
		0.25 * xfrac * (xfrac-2)) * (1-xfrac)) + y) / 6.0;

	    if (y > 32767) y = 32767;
	    if (y < -32767) y = -32767;

	    new_data[i] = ceil(y - 0.5);
	}
    }

    free(sp->data);
    sp->data = new_data;
    sp->sample_rate = new_rate;

    sp->data_length = new_data_length << FRACTION_BITS;
    sp->loop_start = loop_start * (1 << FRACTION_BITS);
    sp->loop_end = loop_end * (1 << FRACTION_BITS);
}

void load_module_samples (SAMPLE * s, int numsamples, int ntsc)
{
    int i;

    for(i = 1; numsamples--; i++, s++)
    {
	Sample *sp;
	char name[23];

	if(!s->data)
	    continue;

	ctl->cmsg(CMSG_INFO, VERB_DEBUG,
		  "MOD Sample %d (%.22s)", i, s->samplename);

	special_patch[i] =
	    (SpecialPatch *)safe_malloc(sizeof(SpecialPatch));
	special_patch[i]->type = INST_MOD;
	special_patch[i]->samples = 1;
	special_patch[i]->sample = sp =
	    (Sample *)safe_malloc(sizeof(Sample));
	memset(sp, 0, sizeof(Sample));
	strncpy(name, s->samplename, 22);
	name[22] = '\0';
	code_convert(name, NULL, 23, NULL, "ASCII");
	if(name[0] == '\0')
	    special_patch[i]->name = NULL;
	else
	    special_patch[i]->name = safe_strdup(name);
	special_patch[i]->sample_offset = 0;

	sp->data = (sample_t *)s->data;
	sp->data_alloced = 1;
	sp->data_length = s->length;
	sp->loop_start = s->loopstart;
	sp->loop_end   = s->loopend;

        /* The sample must be padded out by 1 extra sample, so that
           the interpolation routines won't cause a "pop" by reading
           random data beyond data_length */
	sp->data = (sample_t *) realloc(sp->data,
					(sp->data_length + 1) *
					sizeof(sample_t));
        sp->data[sp->data_length] = 0;

	/* Stereo instruments (SF_STEREO) are dithered by libunimod into mono */
	sp->modes = MODES_UNSIGNED;
	if (s->flags & SF_SIGNED)  sp->modes ^= MODES_UNSIGNED;
	if (s->flags & SF_LOOP)    sp->modes ^= MODES_LOOPING;
	if (s->flags & SF_BIDI)    sp->modes ^= MODES_PINGPONG;
	if (s->flags & SF_REVERSE) sp->modes ^= MODES_REVERSE;
	if (s->flags & SF_16BITS)  sp->modes ^= MODES_16BIT;

#ifdef USE_ENVELOPE
	/* envelope (0,1:attack, 2:sustain, 3,4,5:release) */
	sp->modes |= MODES_ENVELOPE;

	/* attack */
	sp->envelope_offset[0] = env_offset(255);
	sp->envelope_rate[0]   = env_rate(255, 0.0);	/* fastest */
	sp->envelope_offset[1] = sp->envelope_offset[0];
	sp->envelope_rate[1]   = 0; /* skip this stage */
	/* sustain */
	sp->envelope_offset[2] = sp->envelope_offset[1];
	sp->envelope_rate[2]   = 0;
	/* release */
	sp->envelope_offset[3] = env_offset(0);
	sp->envelope_rate[3]   = env_rate(255, 80.0);	/* 80 msec */
	sp->envelope_offset[4] = sp->envelope_offset[3];
	sp->envelope_rate[4]   = 0; /* skip this stage */
	sp->envelope_offset[5] = sp->envelope_offset[4];
	sp->envelope_rate[5]   = 0; /* skip this stage, then the voice is
				       disappeared */
#endif
 	sp->sample_rate = PAL_RATE >> s->divfactor;
	sp->low_freq = 0;
	sp->high_freq = 0x7fffffff;
	sp->root_freq = freq_table[MOD_ROOT_NOTE];
	sp->volume = 1.0;		/* I guess it should use globvol... */
	sp->panning = s->panning == PAN_SURROUND ? 64 : s->panning * 128 / 255;
	sp->note_to_use = 0;
	sp->low_vel = 0;
	sp->high_vel = 127;
	sp->tremolo_sweep_increment =
		sp->tremolo_phase_increment = sp->tremolo_depth =
		sp->vibrato_sweep_increment = sp->vibrato_control_ratio = sp->vibrato_depth = 0;
	sp->cutoff_freq = sp->resonance = sp->tremolo_to_pitch =
		sp->tremolo_to_fc = sp->modenv_to_pitch = sp->modenv_to_fc =
		sp->vel_to_fc = sp->key_to_fc = sp->vel_to_resonance = 0;
	sp->envelope_velf_bpo = sp->modenv_velf_bpo =
		sp->vel_to_fc_threshold = 64;
	sp->key_to_fc_bpo = 60;
	sp->scale_freq = 60;
	sp->scale_factor = 1024;
	memset(sp->envelope_velf, 0, sizeof(sp->envelope_velf));
	memset(sp->envelope_keyf, 0, sizeof(sp->envelope_keyf));
	memset(sp->modenv_velf, 0, sizeof(sp->modenv_velf));
	memset(sp->modenv_keyf, 0, sizeof(sp->modenv_keyf));
	memset(sp->modenv_rate, 0, sizeof(sp->modenv_rate));
	memset(sp->modenv_offset, 0, sizeof(sp->modenv_offset));
	sp->envelope_delay = sp->modenv_delay =
		sp->tremolo_delay = sp->vibrato_delay = 0;
	sp->sample_type = SF_SAMPLETYPE_MONO;
	sp->sf_sample_link = -1;
	sp->sf_sample_index = 0;

	if (sp->data_length >= (1 << (31 - FRACTION_BITS)) - 1)
	    shrink_huge_sample(sp);
	else
	{
	    sp->data_length <<= FRACTION_BITS;
	    sp->loop_start <<= FRACTION_BITS;
	    sp->loop_end <<= FRACTION_BITS;
	}

	/* pitch detection for mod->midi file conversion and surround chorus */
	if (play_mode->id_character == 'M' ||
	    opt_surround_chorus)
	{
	    sp->chord = -1;
	    sp->root_freq_detected = freq_fourier(sp, &(sp->chord));
	    sp->transpose_detected =
		assign_pitch_to_freq(sp->root_freq_detected) -
		assign_pitch_to_freq(sp->root_freq / 1024.0);
	}

	/* If necessary do some anti-aliasing filtering  */
	if (antialiasing_allowed)
	  antialiasing((int16 *)sp->data, sp->data_length / 2,
		       sp->sample_rate, play_mode->rate);

	s->data = NULL;		/* Avoid free-ing */
	s->id = i;
    }
}

{'repo_name': 'RasPlex/OpenPHT', 'stars': '545', 'repo_language': 'C', 'file_name': 'A2Misc.h', 'mime_type': 'text/x-c++', 'hash': -1456447087915531187, 'source_dataset': 'data'}


package org.talend.esb.examples.ebook.parser;

import java.net.URI;
import java.net.URISyntaxException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.talend.esb.examples.ebook.model.Book;
import org.talend.esb.examples.ebook.model.Format;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class BookParser {
    private XPath xpath;

    public BookParser() throws XPathExpressionException {
        XPathFactory xpathfactory = XPathFactory.newInstance();
        this.xpath = xpathfactory.newXPath();
        NamespaceMap namespaceMapmap = new NamespaceMap();
        namespaceMapmap.add("dcterms", "http://purl.org/dc/terms/");
        namespaceMapmap.add("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#");
        namespaceMapmap.add("pgterms", "http://www.gutenberg.org/2009/pgterms/");
        namespaceMapmap.add("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
        namespaceMapmap.add("marcrel", "http://id.loc.gov/vocabulary/relators/");
        namespaceMapmap.add("pgterms", "http://www.gutenberg.org/2009/pgterms/");
        namespaceMapmap.add("dcam", "http://purl.org/dc/dcam/");
        namespaceMapmap.add("cc", "http://web.resource.org/cc/");
        xpath.setNamespaceContext(namespaceMapmap);
    }

    public Book parse(Document doc) throws XPathExpressionException, URISyntaxException {
        Book book = new Book();
        String id = xpath.evaluate("//pgterms:ebook/@rdf:about", doc);
        book.setId(id);
        book.setTitle(xpath.evaluate("//dcterms:title/text()", doc));
        book.setCreator(xpath.evaluate("//dcterms:creator//pgterms:name/text()", doc));
        NodeList files = (NodeList)xpath.evaluate("//pgterms:file", doc, XPathConstants.NODESET);
        //NodeList subjects = (NodeList)xpath.evaluate("//dcterms:subject/rdf:Description/rdf:value", doc, XPathConstants.NODESET);
        for (int c = 0; c < files.getLength(); c++) {
            Format format = parseFormat((Element)files.item(c));
            if (format.getMediaType().startsWith("image")) {
                book.setCover(format.getFile());
            }
            book.getFormats().add(format);
        }
        /*
        for (int c = 0; c < subjects.getLength(); c++) {
            Element subjectEl = (Element)subjects.item(c);
            book.getSubjects().add(new Subject(subjectEl.getTextContent()));
        }
        */

        return book;
    }

    private Format parseFormat(Element file) throws XPathExpressionException {
        Format format = new Format();
        String about = xpath.evaluate("@rdf:about", file);
        try {
            format.setFile(new URI(about));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
        format.setExtent(new Integer(xpath.evaluate("dcterms:extent", file)));
        format.setMediaType(xpath.evaluate("dcterms:format/rdf:Description/rdf:value", file));
        format.setModified(xpath.evaluate("dcterms:modified", file));
        return format;
    }

}

{'repo_name': 'Talend/tesb-rt-se', 'stars': '143', 'repo_language': 'Java', 'file_name': 'RegisterOperation.java', 'mime_type': 'text/x-java', 'hash': 1563524806790031336, 'source_dataset': 'data'}


from oauthlib.common import add_params_to_uri
import foauth.providers

class Coinbase(foauth.providers.OAuth2):
    # General info about the provider
    provider_url = 'https://coinbase.com/'
    docs_url = 'https://coinbase.com/api/doc'
    category = 'Money'

    # URLs to interact with the API
    authorize_url = 'https://coinbase.com/oauth/authorize'
    access_token_url = 'https://coinbase.com/oauth/token'
    api_domain = 'coinbase.com'

    available_permissions = [
        (None, 'View your basic account information'),
        ('merchant', 'Create payment buttons and forms, view your basic user information, edit your merchant settings, and generate new receive addresses'),
        ('balance', 'View your balance'),
        ('addresses', 'View receive addresses and create new ones'),
        ('buttons', 'Create payment buttons'),
        ('buy', 'Buy bitcoin'),
        ('contacts', 'List emails and bitcoin addresses in your contact list'),
        ('orders', 'List merchant orders received'),
        ('sell', 'Sell bitcoin'),
        ('transactions', 'View your transaction history'),
        ('send', 'Debit an unlimited amount of money from your account'),
        ('request', 'Request money from your account'),
        ('transfers', 'List bitcoin buy and sell history'),
        ('recurring_payments', 'List your recurring payments'),
        ('oauth_apps', "List the other apps you've authorized"),
        ('all', 'All of the above'),
    ]

    def get_authorize_params(self, redirect_uri, scopes):
        # Always request at least user information
        scopes.append('user')
        return super(Coinbase, self).get_authorize_params(redirect_uri, scopes)

    def get_user_id(self, key):
        r = self.api(key, self.api_domain, u'/api/v1/users')
        return r.json()[u'users'][0][u'user'][u'id']

{'repo_name': 'foauth/foauth.org', 'stars': '188', 'repo_language': 'Python', 'file_name': 'providers.py', 'mime_type': 'text/x-python', 'hash': -7474274584349538797, 'source_dataset': 'data'}


dnl Process this file with autoconf to produce a configure script. -*-m4-*-
dnl
dnl %CopyrightBegin%
dnl
dnl Copyright Ericsson AB 2018-2020. All Rights Reserved.
dnl
dnl Licensed under the Apache License, Version 2.0 (the "License");
dnl you may not use this file except in compliance with the License.
dnl You may obtain a copy of the License at
dnl
dnl     http://www.apache.org/licenses/LICENSE-2.0
dnl
dnl Unless required by applicable law or agreed to in writing, software
dnl distributed under the License is distributed on an "AS IS" BASIS,
dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
dnl See the License for the specific language governing permissions and
dnl limitations under the License.
dnl
dnl %CopyrightEnd%
dnl

dnl define([AC_CACHE_LOAD], )dnl
dnl define([AC_CACHE_SAVE], )dnl

AC_INIT(vsn.mk)

if test -z "$ERL_TOP" || test ! -d "$ERL_TOP" ; then
  AC_CONFIG_AUX_DIRS(autoconf)
else
  erl_top=${ERL_TOP}
  AC_CONFIG_AUX_DIRS($erl_top/erts/autoconf)
fi

if test "X$host" != "Xfree_source" -a "X$host" != "Xwin32"; then
    AC_CANONICAL_HOST
else
    host_os=win32
fi

LM_PRECIOUS_VARS

if test "$cross_compiling" = "yes"; then
    CROSS_COMPILING=yes
else
    CROSS_COMPILING=no
fi
AC_SUBST(CROSS_COMPILING)

ERL_XCOMP_SYSROOT_INIT

AC_PROG_CC
LM_WINDOWS_ENVIRONMENT

ERL_DED

dnl
dnl SSL, SSH and CRYPTO need the OpenSSL libraries
dnl
dnl Check flags --with-ssl, --without-ssl --with-ssl=PATH.
dnl If no option is given or --with-ssl is set without a path then we
dnl search for OpenSSL libraries and header files in the standard locations.
dnl If set to --without-ssl we disable the use of SSL, SSH and CRYPTO.
dnl If set to --with-ssl=PATH we use that path as the prefix, i.e. we
dnl use "PATH/include" and "PATH/lib".

AC_CHECK_SIZEOF(void *)

std_ssl_locations="/usr/local /usr/sfw /usr /opt/local /usr/pkg /usr/local/openssl /usr/local/opt/openssl /usr/lib/openssl /usr/openssl /usr/local/ssl /usr/lib/ssl /usr/ssl /"

AC_ARG_WITH(ssl-zlib,
AS_HELP_STRING([--with-ssl-zlib=PATH],
               [specify location of ZLib to be used by OpenSSL])
AS_HELP_STRING([--with-ssl-zlib],
               [link SSL with  Zlib (default if found)])
AS_HELP_STRING([--without-ssl-zlib],
               [don't link SSL with ZLib]))

if  test "x$with_ssl_zlib" = "xno"; then
	SSL_LINK_WITH_ZLIB=no
	STATIC_ZLIB_LIBS=
elif test "x$with_ssl_zlib" = "xyes" || test "x$with_ssl_zlib" = "x"; then
	if test $erl_xcomp_without_sysroot = yes; then
		AC_MSG_WARN([Cannot search for zlib; missing cross system root (erl_xcomp_sysroot).])
		SSL_LINK_WITH_ZLIB=no
		STATIC_ZLIB_LIBS=
	elif  test "$host_os" = "win32"; then
		SSL_LINK_WITH_ZLIB=no
		STATIC_ZLIB_LIBS=
	else
		SSL_LINK_WITH_ZLIB=no
		STATIC_ZLIB_LIBS=
		AC_MSG_CHECKING(for static ZLib to be used by SSL in standard locations)
		for rdir in $std_ssl_locations; do
			dir="$erl_xcomp_sysroot$rdir"
			if test "x$ac_cv_sizeof_void_p" = "x8"; then
				if test -f "$dir/lib64/libz.a"; then
					SSL_LINK_WITH_ZLIB=yes
					STATIC_ZLIB_LIBS="$dir/lib64/libz.a"
					break
				elif test -f "$dir/lib/64/libz.a"; then
					SSL_LINK_WITH_ZLIB=yes
					STATIC_ZLIB_LIBS="$dir/lib/64/libz.a"
					break
				fi
			fi
			if test -f "$dir/lib/libz.a"; then
					SSL_LINK_WITH_ZLIB=yes
				STATIC_ZLIB_LIBS="$dir/lib/libz.a"
				break
			fi
		done
		if test "x$SSL_LINK_WITH_ZLIB" = "xno"; then
		       	AC_MSG_RESULT([no])
		else
			AC_MSG_RESULT([$STATIC_ZLIB_LIBS])
		fi
	fi
else
	SSL_LINK_WITH_ZLIB=no
	STATIC_ZLIB_LIBS=
	if test -f "$with_ssl_zlib/libz.a"; then
		SSL_LINK_WITH_ZLIB=yes
		STATIC_ZLIB_LIBS=$with_ssl_zlib/libz.a
	elif test -f "$with_ssl_zlib/lib/libz.a"; then
		SSL_LINK_WITH_ZLIB=yes
		STATIC_ZLIB_LIBS=$with_ssl_zlib/lib/libz.a
	fi
	if test "x$ac_cv_sizeof_void_p" = "x8"; then
		if test -f "$with_ssl_zlib/lib64/libz.a"; then
			SSL_LINK_WITH_ZLIB=yes
			STATIC_ZLIB_LIBS=$with_ssl_zlib/lib64/libz.a
		elif test -f "$with_ssl_zlib/lib/64/libz.a"; then
			SSL_LINK_WITH_ZLIB=yes
			STATIC_ZLIB_LIBS=$with_ssl_zlib/lib/64/libz.a
		fi
	fi
	if test "x$SSL_LINK_WITH_ZLIB" = "xno"; then
	       	AC_MSG_ERROR(Invalid path to option --with-ssl-zlib=PATH)
	fi
fi

AC_ARG_WITH(ssl,
AS_HELP_STRING([--with-ssl=PATH], [specify location of OpenSSL include and lib])
AS_HELP_STRING([--with-ssl], [use SSL (default)])
AS_HELP_STRING([--without-ssl], [don't use SSL]))

AC_ARG_WITH(ssl-incl,
AS_HELP_STRING([--with-ssl-incl=PATH], [location of OpenSSL include dir, if different than specified by --with-ssl=PATH]),
[
case X$with_ssl in
    X | Xyes | Xno) AC_MSG_ERROR([--with-ssl-incl=PATH set without --with-ssl=PATH]);;
esac
],
[with_ssl_incl=$with_ssl]) #default

AC_ARG_WITH(ssl-rpath,
AS_HELP_STRING([--with-ssl-rpath=yes|no|PATHS],
               [runtime library path for OpenSSL. Default is "yes", which equates to a
	       number of standard locations. If "no", then no runtime
	       library paths will be used. Anything else should be a
	       comma separated list of paths.]),
[
case X$with_ssl in
    Xno) AC_MSG_ERROR([--with-ssl-rpath set without --with-ssl]);;
esac
],
[with_ssl_rpath=yes]) #default

AC_ARG_ENABLE(dynamic-ssl-lib,
AS_HELP_STRING([--disable-dynamic-ssl-lib],
               [disable using dynamic openssl libraries]),
[ case "$enableval" in
    no) enable_dynamic_ssl=no ;;
    *)  enable_dynamic_ssl=yes ;;
  esac ], enable_dynamic_ssl=yes)

AC_ARG_ENABLE(evp-dh,
AS_HELP_STRING([--disable-evp-dh],
	       [intentionally undocumented workaround]),
[ case "$enableval" in
    no)   DISABLE_EVP_DH=1;;
    *)    DISABLE_EVP_DH=0;;
  esac ], DISABLE_EVP_DH=0)

#----------------------------------------------------------------------
# We actually might do the SSL tests twice due to late discovery of
# kerberos problems with static linking, in case we redo it all trying
# dynamic SSL libraries instead.
#----------------------------------------------------------------------

ssl_done=no

while test "x$ssl_done" != "xyes"; do

ssl_done=yes # Default only one run

# Remove all SKIP files from previous runs
for a in ssl crypto ssh; do
  rm -f "$ERL_TOP/lib/$a/SKIP"
done

SSL_DYNAMIC_ONLY=$enable_dynamic_ssl
SSL_STATIC_ONLY=no

case "$erl_xcomp_without_sysroot-$with_ssl" in
  yes-* | no-no)
    SSL_APP=
    CRYPTO_APP=
    SSH_APP=
    if test "$with_ssl" = "no"; then
	skip="User gave --without-ssl option"
    else
	skip="Cannot search for ssl; missing cross system root (erl_xcomp_sysroot)."
    fi
    for a in ssl crypto ssh; do
        echo "$skip" > $ERL_TOP/lib/$a/SKIP
    done
    ;;
  no-yes | no- )
    # On windows, we could try to find the installation
    # of Shining Light OpenSSL, which can be found by poking in
    # the uninstall section in the registry, it's worth a try...
    extra_dir=""
    if  test "$host_os" = "win32"; then
    	AC_CHECK_PROG(REGTOOL, reg_query.sh, reg_query.sh, false)
	if test "$ac_cv_prog_REGTOOL" != false; then
	   	if test "x$ac_cv_sizeof_void_p" = "x8"; then
		   rp="HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/OpenSSL (64-bit)_is1"
		else
		   rp="HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/OpenSSL_is1"
		fi
		key="Inno Setup: App Path"
		if "$ac_cv_prog_REGTOOL" "$rp" "$key" > /dev/null; then
			ssl_install_dir=`"$ac_cv_prog_REGTOOL" "$rp" "$key"`
			extra_dir=`w32_path.sh -u "$ssl_install_dir"`
		fi
	fi
    fi
    # We search for OpenSSL in the common OS standard locations.
    SSL_APP=ssl
    CRYPTO_APP=crypto
    SSH_APP=ssh

    SSL_CRYPTO_LIBNAME=crypto
    SSL_SSL_LIBNAME=ssl
    SSL_EXTRA_LIBS=""

    if  test "$host_os" = "win32" ; then
    	if test "x$ac_cv_sizeof_void_p" = "x8"; then
	  std_win_ssl_locations="/mnt/c/OpenSSL-Win64 /c/OpenSSL-Win64 /mnt/c/opt/local64/pgm/OpenSSL /opt/local64/pgm/OpenSSL /cygdrive/c/OpenSSL-Win64"
	  lib_bits=64
	else
	  std_win_ssl_locations="/mnt/c/OpenSSL-Win32 /c/OpenSSL-Win32 /mnt/c/OpenSSL /c/OpenSSL /cygdrive/c/OpenSSL /opt/local/pgm/OpenSSL /opt/local32/pgm/OpenSSL /mnt/c/opt/local/pgm/OpenSSL /mnt/c/opt/local32/pgm/OpenSSL /cygdrive/c/OpenSSL-Win32"
	  lib_bits=32
	fi
    else
        std_win_ssl_locations=""
    fi

    AC_MSG_CHECKING(for OpenSSL >= 0.9.8c in standard locations)
    for rdir in "$extra_dir" $std_win_ssl_locations $std_ssl_locations; do
	dir="$erl_xcomp_sysroot$rdir"
	if test -f "$erl_xcomp_isysroot$rdir/include/openssl/opensslv.h"; then
		is_real_ssl=yes
		SSL_INCDIR="$dir"
		if test "$host_os" = "win32" ; then
			if test -f "$dir/lib/VC/libeay32.lib"; then
				SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
				SSL_LIBDIR="$dir/lib/VC"
				SSL_CRYPTO_LIBNAME=libeay32
				SSL_SSL_LIBNAME=ssleay32
			elif test -f "$dir/lib/VC/openssl.lib"; then
				SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
				SSL_LIBDIR="$dir/lib/VC"
			elif test -f "$dir/lib/VC/libeay32MD.lib"; then
		            SSL_CRYPTO_LIBNAME=libeay32MD
		            SSL_SSL_LIBNAME=ssleay32MD
			    if test "x$enable_dynamic_ssl" = "xno" && \
	                       test -f "$dir/lib/VC/static/libeay32MD.lib"; then
				  SSL_RUNTIME_LIBDIR="$rdir/lib/VC/static"
				  SSL_LIBDIR="$dir/lib/VC/static"
		            else
			          SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
				  SSL_LIBDIR="$dir/lib/VC"
                            fi
			elif test -f "$dir/lib/libeay32.lib"; then
				SSL_RUNTIME_LIBDIR="$rdir/lib"
				SSL_LIBDIR="$dir/lib"
				SSL_CRYPTO_LIBNAME=libeay32
				SSL_SSL_LIBNAME=ssleay32
			elif test -f "$dir/lib/VC/libcrypto${lib_bits}MD.lib"; then
		            SSL_CRYPTO_LIBNAME=libcrypto${lib_bits}MD
			    # NOTE: Additional ugly extra libs at the end
		            SSL_SSL_LIBNAME="libssl${lib_bits}MD"
			    if test "x$enable_dynamic_ssl" = "xno" && \
	                       test -f "$dir/lib/VC/static/$SSL_CRYPTO_LIBNAME.lib"; then
       			          SSL_EXTRA_LIBS="-lCRYPT32 -lWS2_32"
				  SSL_RUNTIME_LIBDIR="$rdir/lib/VC/static"
				  SSL_LIBDIR="$dir/lib/VC/static"
		            else
			          SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
				  SSL_LIBDIR="$dir/lib/VC"
                            fi
			elif test -f "$dir/lib/openssl.lib"; then
				SSL_RUNTIME_LIBDIR="$rdir/lib"
				SSL_LIBDIR="$dir/lib"
			else
				is_real_ssl=no
			fi
		elif test -f "$dir/lib/powerpc/libsslcrypto.a"; then
			SSL_CRYPTO_LIBNAME=sslcrypto
			SSL_LIBDIR="$dir/lib/powerpc/"
			SSL_RUNTIME_LIBDIR="$rdir/lib/powerpc/"
		else
			if test "x$ac_cv_sizeof_void_p" = "x8"; then
				if test -f "$dir/lib64/libcrypto.a"; then
					SSL_RUNTIME_LIBDIR="$rdir/lib64"
					SSL_LIBDIR="$dir/lib64"
				elif test -f "$dir/lib/64/libcrypto.a"; then
					SSL_RUNTIME_LIBDIR="$rdir/lib/64"
					SSL_LIBDIR="$dir/lib/64"
				elif test -f "$dir/lib64/libcrypto.so"; then
					SSL_RUNTIME_LIBDIR="$rdir/lib64"
					SSL_LIBDIR="$dir/lib64"
				elif test -f "$dir/lib/64/libcrypto.so"; then
					SSL_RUNTIME_LIBDIR="$rdir/lib/64"
					SSL_LIBDIR="$dir/lib/64"
				else
					SSL_RUNTIME_LIBDIR="$rdir/lib"
					SSL_LIBDIR="$dir/lib"
				fi
			else
				SSL_RUNTIME_LIBDIR="$rdir/lib"
				SSL_LIBDIR="$dir/lib"
			fi
		fi
		if test '!' -f "$SSL_LIBDIR/lib${SSL_CRYPTO_LIBNAME}.a"; then
			SSL_DYNAMIC_ONLY=yes
		elif test '!' -f "$SSL_LIBDIR/lib${SSL_CRYPTO_LIBNAME}.so" -a '!' -f "$SSL_LIBDIR/lib${SSL_CRYPTO_LIBNAME}.dylib"; then
			SSL_STATIC_ONLY=yes
		fi
		SSL_BINDIR="$rdir/bin"
		if test "x$is_real_ssl" = "xyes" ; then
			SSL_INCLUDE="-I$dir/include"
			old_CPPFLAGS=$CPPFLAGS
			CPPFLAGS=$SSL_INCLUDE
			AC_EGREP_CPP(^yes.?$,[
#include <openssl/opensslv.h>
#if OPENSSL_VERSION_NUMBER >= 0x0090803fL
yes
#endif
			],[
			ssl_found=yes
			],[
			SSL_APP=
			ssl_found=no
         		])
         		CPPFLAGS=$old_CPPFLAGS
			if test "x$ssl_found" = "xyes"; then
			   	if test "x$host_os" = "xwin32" ; then
				   	ssl_linkable=yes
				elif test "x${SSL_CRYPTO_LIBNAME}" = "xsslcrypto"; then
				# This should only be triggered seen OSE
					ssl_linkable=yes
				else
					saveCFLAGS="$CFLAGS"
 					saveLDFLAGS="$LDFLAGS"
					saveLIBS="$LIBS"
 					CFLAGS="$CFLAGS $SSL_INCLUDE"
					if test "x$SSL_STATIC_ONLY" = "xyes"; then
						LIBS="${SSL_LIBDIR}/lib${SSL_CRYPTO_LIBNAME}.a"
					else
						LDFLAGS="$LDFLAGS -L$SSL_LIBDIR"
						LIBS="$LIBS -l${SSL_CRYPTO_LIBNAME}"
					fi
 					AC_TRY_LINK([
					#include <stdio.h>
 					#include <openssl/hmac.h>],
 					[
					HMAC(0, 0, 0, 0, 0, 0, 0);
 					],
 					[ssl_linkable=yes],
 					[ssl_linkable=no])
 					CFLAGS="$saveCFLAGS"
 					LDFLAGS="$saveLDFLAGS"
					LIBS="$saveLIBS"
				fi
 			fi
	 		if test "x$ssl_found" = "xyes" && test "x$ssl_linkable" = "xyes"; then
			 	AC_MSG_RESULT([$dir])
	   			break;
         		fi
		fi
       fi
    done

    if test "x$ssl_found" != "xyes" ; then
	dnl
	dnl If no SSL found above, check whether we are running on OpenBSD.
	dnl
	case $host_os in
	openbsd*)
	       if test -f "$erl_xcomp_isysroot/usr/include/openssl/opensslv.h"; then
		  # Trust OpenBSD to have everything the in the correct locations.
		  ssl_found=yes
		  ssl_linkable=yes
		  SSL_INCDIR="$erl_xcomp_sysroot/usr"
	          AC_MSG_RESULT([$SSL_INCDIR])
		  SSL_RUNTIME_LIB="/usr/lib"
		  SSL_LIB="$erl_xcomp_sysroot/usr/lib"
		  SSL_BINDIR="/usr/sbin"
		  dnl OpenBSD requires us to link with -L and -l
		  SSL_DYNAMIC_ONLY="yes"
		fi
		;;
	esac
    fi
dnl		Now, certain linuxes have a 64bit libcrypto
dnl		that cannot build shared libraries (i.e. not PIC)
dnl		One could argue that this is wrong, but
dnl		so it is - be adoptable
    if test "$ssl_found" = "yes" && test "$ssl_linkable" = "yes" && test "$SSL_DYNAMIC_ONLY" != "yes"; then
	case $host_os in
		linux*)
			saveCFLAGS="$CFLAGS"
 			saveLDFLAGS="$LDFLAGS"
			saveLIBS="$LIBS"
 			CFLAGS="$DED_CFLAGS $SSL_INCLUDE"
 			LDFLAGS="$DED_LDFLAGS"
			LIBS="$SSL_LIBDIR/libcrypto.a $STATIC_ZLIB_LIBS"
 			AC_TRY_LINK([
			#include <stdio.h>
 			#include <openssl/hmac.h>],
 			[
			HMAC(0, 0, 0, 0, 0, 0, 0);
 			],
 			[ssl_dyn_linkable=yes],
 			[ssl_dyn_linkable=no])
 			CFLAGS="$saveCFLAGS"
 			LDFLAGS="$saveLDFLAGS"
			LIBS="$saveLIBS"
			if test "x$ssl_dyn_linkable" != "xyes"; then
				SSL_DYNAMIC_ONLY=yes
				AC_MSG_WARN([SSL will be linked against dynamic lib as static lib is not purely relocatable])
			fi
			;;
	esac
    fi

    if test "x$ssl_found" != "xyes" || test  "x$ssl_linkable" != "xyes"; then
       if test "x$ssl_found" = "xyes"; then
       		AC_MSG_RESULT([found; but not usable])
       else
       		AC_MSG_RESULT([no])
       fi
       SSL_APP=
       CRYPTO_APP=
       SSH_APP=
       AC_MSG_WARN([No (usable) OpenSSL found, skipping ssl, ssh and crypto applications])

       for a in ssl crypto ssh; do
           echo "No usable OpenSSL found" > $ERL_TOP/lib/$a/SKIP
       done
    fi
    ;;
  *)
    # Option given with PATH to package
    if test ! -d "$with_ssl" ; then
       AC_MSG_ERROR(Invalid path to option --with-ssl=PATH)
    fi
    if test ! -d "$with_ssl_incl" ; then
       AC_MSG_ERROR(Invalid path to option --with-ssl-incl=PATH)
    fi
    SSL_INCDIR="$with_ssl_incl"
    SSL_CRYPTO_LIBNAME=crypto
    SSL_SSL_LIBNAME=ssl
    SSL_EXTRA_LIBS=""
    if test "x$host_os" = "xwin32" && test -d "$with_ssl/lib/VC"; then
	if test -f "$with_ssl/lib/VC/libeay32.lib"; then
	    SSL_LIBDIR="$with_ssl/lib/VC"
	    SSL_CRYPTO_LIBNAME=libeay32
	    SSL_SSL_LIBNAME=ssleay32
	elif test -f "$with_ssl/lib/VC/openssl.lib"; then
	    SSL_LIBDIR="$with_ssl/lib/VC"
	elif test -f $with_ssl/lib/VC/libeay32MD.lib; then
	    SSL_CRYPTO_LIBNAME=libeay32MD
            SSL_SSL_LIBNAME=ssleay32MD
	    if test "x$enable_dynamic_ssl" = "xno" && \
	       test -f  $with_ssl/lib/VC/static/libeay32MD.lib; then
		SSL_LIBDIR="$with_ssl/lib/VC/static"
	    else
		SSL_LIBDIR="$with_ssl/lib/VC"
            fi
	elif test -f "$dir/lib/VC/libcrypto${lib_bits}MD.lib"; then
            SSL_CRYPTO_LIBNAME=libcrypto${lib_bits}MD
	    # NOTE: Additional ugly extra libs at the end
            SSL_SSL_LIBNAME="libssl${lib_bits}MD"
	    if test "x$enable_dynamic_ssl" = "xno" && \
               test -f "$dir/lib/VC/static/$SSL_CRYPTO_LIBNAME.lib"; then
	          SSL_EXTRA_LIBS="-lCRYPT32 -lWS2_32"
		  SSL_RUNTIME_LIBDIR="$rdir/lib/VC/static"
		  SSL_LIBDIR="$dir/lib/VC/static"
            else
	          SSL_RUNTIME_LIBDIR="$rdir/lib/VC"
		  SSL_LIBDIR="$dir/lib/VC"
            fi
	elif test -f "$with_ssl/lib/libeay32.lib"; then
	    SSL_LIBDIR="$with_ssl/lib"
	    SSL_CRYPTO_LIBNAME=libeay32
	    SSL_SSL_LIBNAME=ssleay32
	elif test -f "$dir/lib/openssl.lib"; then
	    SSL_RUNTIME_LIBDIR="$rdir/lib"
	    SSL_LIBDIR="$dir/lib"
	    SSL_CRYPTO_LIBNAME=libcrypto
	    SSL_SSL_LIBNAME=openssl
	else
	    # This probably wont work, but that's what the user said, so...
	    SSL_LIBDIR="$with_ssl/lib"
	fi
    elif test -f "$dir/lib/powerpc/libsslcrypto.a"; then
	    SSL_CRYPTO_LIBNAME=sslcrypto
	    SSL_LIBDIR="$with_ssl/lib/powerpc/"
    elif test "x$ac_cv_sizeof_void_p" = "x8"; then
	if test -f "$with_ssl/lib64/libcrypto.a"; then
		SSL_LIBDIR="$with_ssl/lib64"
	elif test -f "$with_ssl/lib/64/libcrypto.a"; then
		SSL_LIBDIR="$with_ssl/lib/64"
	elif test -f "$with_ssl/lib64/libcrypto.so"; then
		SSL_LIBDIR="$with_ssl/lib64"
	elif test -f "$with_ssl/lib/64/libcrypto.so"; then
		SSL_LIBDIR="$with_ssl/lib/64"
	else
		SSL_LIBDIR="$with_ssl/lib"
	fi
    else
	SSL_LIBDIR="$with_ssl/lib"
    fi
    if test '!' -f "${SSL_LIBDIR}/lib${SSL_CRYPTO_LIBNAME}.a"; then
	SSL_DYNAMIC_ONLY=yes
    elif test '!' -f ${SSL_LIBDIR}/lib${SSL_CRYPTO_LIBNAME}.so -a '!' -f "$SSL_LIBDIR/lib${SSL_CRYPTO_LIBNAME}.dylib"; then
    	SSL_STATIC_ONLY=yes
    fi
    SSL_INCLUDE="-I$with_ssl_incl/include"
    SSL_APP=ssl
    CRYPTO_APP=crypto
    SSH_APP=ssh
    if test "$cross_compiling" = "yes"; then
	SSL_RUNTIME_LIBDIR=`echo "$SSL_LIBDIR" | sed -n "s|^$erl_xcomp_sysroot\(/*\)\(.*\)\$|/\2|p"`
    else
	SSL_RUNTIME_LIBDIR="$SSL_LIBDIR"
    fi
esac

if test "x$SSL_APP" != "x" ; then
    dnl We found openssl, now check if we use kerberos 5 support
    dnl FIXME: Do we still support platforms that have Kerberos?
    AC_MSG_CHECKING(for OpenSSL kerberos 5 support)
    old_CPPFLAGS=$CPPFLAGS
    CPPFLAGS=$SSL_INCLUDE
    AC_EGREP_CPP(^yes$,[
#include <openssl/opensslv.h>
#include <openssl/opensslconf.h>
#if OPENSSL_VERSION_NUMBER < 0x1010000fL && !defined(OPENSSL_NO_KRB5)
yes
#endif
      ],[
      AC_MSG_RESULT([yes])
      ssl_krb5_enabled=yes
      if test "x$SSL_DYNAMIC_ONLY" != "xyes"; then
          if test -f "$SSL_LIBDIR/libkrb5.a"; then
              SSL_LINK_WITH_KERBEROS=yes
	      STATIC_KERBEROS_LIBS="$SSL_LIBDIR/libkrb5.a"
	      if test -f "$SSL_LIBDIR/libkrb5support.a"; then
		  STATIC_KERBEROS_LIBS="$STATIC_KERBEROS_LIBS $SSL_LIBDIR/libkrb5support.a"
	      fi
	      if test -f "$SSL_LIBDIR/libk5crypto.a"; then
		  STATIC_KERBEROS_LIBS="$STATIC_KERBEROS_LIBS $SSL_LIBDIR/libk5crypto.a"
	      fi
	      if test -f "$SSL_LIBDIR/libresolv.a"; then
		  STATIC_KERBEROS_LIBS="$STATIC_KERBEROS_LIBS $SSL_LIBDIR/libresolv.a"
	      fi
	      if test -f "$SSL_LIBDIR/libcom_err.a"; then
		  STATIC_KERBEROS_LIBS="$STATIC_KERBEROS_LIBS $SSL_LIBDIR/libcom_err.a"
	      fi
          else
	      AC_MSG_WARN([Kerberos needed but no kerberos static libraries found])
	      AC_MSG_WARN([Rescanning for dynamic SSL libraries])
	      enable_dynamic_ssl=yes
	      ssl_done=no
	      SSL_LINK_WITH_KERBEROS=no
	      STATIC_KERBEROS_LIBS=""
	      ssl_krb5_enabled=no
	      SSL_WITH_KERBEROS=no
          fi
      else
	      SSL_LINK_WITH_KERBEROS=no
	      STATIC_KERBEROS_LIBS=""
      fi
      ],[
      AC_MSG_RESULT([no])
      ssl_krb5_enabled=no
      SSL_WITH_KERBEROS=no
      ])
    CPPFLAGS=$old_CPPFLAGS
    SSL_KRB5_INCLUDE=
    if test "x$ssl_krb5_enabled" = "xyes" ; then
        AC_MSG_CHECKING(for krb5.h in standard locations)
	for dir in $extra_dir "$SSL_INCDIR/include" "$SSL_INCDIR/include/openssl" \
		"$SSL_INCDIR/include/kerberos" \
		"$erl_xcomp_isysroot/cygdrive/c/kerberos/include" \
		"$erl_xcomp_isysroot/usr/local/kerberos/include" \
		"$erl_xcomp_isysroot/usr/kerberos/include" \
		"$erl_xcomp_isysroot/usr/include"
	do
            if test -f "$dir/krb5.h" ; then
                SSL_KRB5_INCLUDE="$dir"
		break
            fi
        done
        if test "x$SSL_KRB5_INCLUDE" = "x" ; then
	    AC_MSG_RESULT([not found])
	    SSL_APP=
	    CRYPTO_APP=
	    SSH_APP=
	    AC_MSG_WARN([OpenSSL is configured for kerberos but no krb5.h found])
	    for a in ssl crypto ssh ; do
	 	echo "OpenSSL is configured for kerberos but no krb5.h found" > $ERL_TOP/lib/$a/SKIP
	    done
        else
            AC_MSG_RESULT([found in $SSL_KRB5_INCLUDE])
            SSL_INCLUDE="$SSL_INCLUDE -I$SSL_KRB5_INCLUDE"
        fi
    fi
fi

done # while test ssl_done != yes

SSL_DED_LD_RUNTIME_LIBRARY_PATH=
ded_ld_rflg="$DED_LD_FLAG_RUNTIME_LIBRARY_PATH"

case "$with_ssl_rpath" in

yes)   # Use standard lib locations for ssl runtime library path

  if test "$SSL_APP" != "" && test "$SSL_DYNAMIC_ONLY" = "yes" && test "$ded_ld_rflg" != ""; then

    AC_MSG_CHECKING(for ssl runtime library path to use)

    libdirs="/lib"

    if test "$ac_cv_sizeof_void_p" = "8"; then
	dir_lib64=no
	dir_lib_64=no

	case "$SSL_RUNTIME_LIBDIR" in
	    */lib/64 | */lib/64/ ) dir_lib_64=yes;;
	    */lib64 | */lib64/ ) dir_lib64=yes;;
	    *) ;;
	esac

	for dir in $std_ssl_locations; do
	    test $dir_lib_64 = no &&
	    	test -d "$erl_xcomp_sysroot$dir/lib/64" &&
		    dir_lib_64=yes
	    test $dir_lib64 = no &&
		test -d "$erl_xcomp_sysroot$dir/lib64" &&
		    dir_lib64=yes
	done

	test $dir_lib_64 = yes && libdirs="/lib/64 $libdirs"
	test $dir_lib64 = yes && libdirs="/lib64 $libdirs"
    fi

    for type in std x_std curr; do

        ded_ld_rpath="$ded_ld_rflg$SSL_RUNTIME_LIBDIR"
	rpath="$SSL_RUNTIME_LIBDIR"

	if test $type != curr; then
	    for ldir in $libdirs; do
		for dir in $std_ssl_locations; do
		    test "$SSL_LIBDIR" != "$dir$ldir" || continue
		    test $type != x_std || test -d "$dir$ldir" || continue
		    if test "$dir" = "/"; then
			libdir="$ldir"
		    else
			libdir="$dir$ldir"
		    fi
		    ded_ld_rpath="$ded_ld_rpath $ded_ld_rflg$libdir"
		    rpath="$rpath:$libdir"
                done
	    done
	fi

	saveCFLAGS="$CFLAGS"
	saveLDFLAGS="$LDFLAGS"
	saveLIBS="$LIBS"
	CFLAGS="$CFLAGS $SSL_INCLUDE"
	LDFLAGS="$LDFLAGS $ld_rpath -L$SSL_LIBDIR"
	LIBS="-lcrypto"
	AC_TRY_LINK([
                         #include <stdio.h>
                         #include <openssl/hmac.h>
                    ],
                    [
			 HMAC(0, 0, 0, 0, 0, 0, 0);
                    ],
                    [rpath_success=yes],
                    [rpath_success=no])
	CFLAGS="$saveCFLAGS"
	LDFLAGS="$saveLDFLAGS"
	LIBS="$saveLIBS"

	test "$rpath_success" = "yes" && break
    done

    test "$rpath_success" = "yes" || { ded_ld_rpath=; rpath=; }

    SSL_DED_LD_RUNTIME_LIBRARY_PATH="$ded_ld_rpath"

    AC_MSG_RESULT([$rpath])
    test "$rpath" != "" || AC_MSG_WARN([Cannot set run path during linking])
  fi
  ;;

no)   # Use no ssl runtime library path
  SSL_DED_LD_RUNTIME_LIBRARY_PATH=
  ;;

*)    # Use ssl runtime library paths set by --with-ssl-rpath (without any check)
  ded_ld_rpath=
  delimit=
  for dir in `echo $with_ssl_rpath | sed "s/,/ /g"`; do
      ded_ld_rpath="$ded_ld_rpath$delimit$ded_ld_rflg$dir"
      delimit=" "
  done
  SSL_DED_LD_RUNTIME_LIBRARY_PATH="$ded_ld_rpath"
  ;;

esac

AC_ARG_ENABLE(fips,
AS_HELP_STRING([--enable-fips], [enable OpenSSL FIPS mode support])
AS_HELP_STRING([--disable-fips], [disable OpenSSL FIPS mode support (default)]),
[ case "$enableval" in
    yes) enable_fips_support=yes ;;
    *)   enable_fips_support=no ;;
  esac ], enable_fips_support=no)

if test "x$enable_fips_support" = "xyes" && test "$CRYPTO_APP" != ""; then
   saveCFLAGS="$CFLAGS"
   saveLDFLAGS="$LDFLAGS"
   saveLIBS="$LIBS"
   CFLAGS="$CFLAGS $SSL_INCLUDE"
   LDFLAGS="$LDFLAGS $ded_ld_rpath -L$SSL_LIBDIR"
   LIBS="-lcrypto"
   AC_CHECK_FUNC([FIPS_mode_set],
   [SSL_FLAGS="-DFIPS_SUPPORT"],
   [SSL_FLAGS=])
   CFLAGS="$saveCFLAGS"
   LDFLAGS="$saveLDFLAGS"
   LIBS="$saveLIBS"
else
   SSL_FLAGS=
fi

AC_SUBST(SSL_INCLUDE)
AC_SUBST(SSL_INCDIR)
AC_SUBST(SSL_LIBDIR)
AC_SUBST(SSL_FLAGS)
AC_SUBST(SSL_CRYPTO_LIBNAME)
AC_SUBST(SSL_SSL_LIBNAME)
AC_SUBST(SSL_EXTRA_LIBS)
AC_SUBST(SSL_DED_LD_RUNTIME_LIBRARY_PATH)
AC_SUBST(SSL_DYNAMIC_ONLY)
AC_SUBST(SSL_LINK_WITH_KERBEROS)
AC_SUBST(STATIC_KERBEROS_LIBS)
AC_SUBST(SSL_LINK_WITH_ZLIB)
AC_SUBST(STATIC_ZLIB_LIBS)
AC_SUBST(DISABLE_EVP_DH)

AC_OUTPUT(c_src/$host/Makefile:c_src/Makefile.in)

{'repo_name': 'erlang/otp', 'stars': '8441', 'repo_language': 'Erlang', 'file_name': 'vxworks_resolv.c', 'mime_type': 'text/x-c', 'hash': -324556675746486645, 'source_dataset': 'data'}


import { reaction } from "mobx";
import {
  commands,
  Comment,
  CommentAuthorInformation,
  CommentController,
  CommentMode,
  comments,
  CommentThread,
  CommentThreadCollapsibleState,
  MarkdownString,
  Range,
  Selection,
  TextDocument,
  TextEditorRevealType,
  Uri,
  window
} from "vscode";
import { SMALL_ICON_URL } from "../constants";
import { store } from "../store";
import { getFileUri, getStepFileUri } from "../utils";

const CONTROLLER_ID = "codetour";
const CONTROLLER_LABEL = "CodeTour";

let id = 0;

const SHELL_SCRIPT_PATTERN = /^>>\s+(.*)$/gm;
const COMMAND_PATTERN = /(\(command:[\w+\.]+\?)(\[[^\]]+\])/gm;
const TOUR_REFERENCE_PATTERN = /(?:\[([^\]]+)\])?\[([^\]#]+)?(?:#(\d+))?\](?!\()/gm;

export class CodeTourComment implements Comment {
  public id: string = (++id).toString();
  public contextValue: string = "";
  public author: CommentAuthorInformation = {
    name: CONTROLLER_LABEL,
    iconPath: Uri.parse(SMALL_ICON_URL)
  };
  public body: MarkdownString;

  constructor(
    content: string,
    public label: string = "",
    public parent: CommentThread,
    public mode: CommentMode
  ) {
    const body =
      mode === CommentMode.Preview
        ? this.generatePreviewContent(content)
        : content;

    this.body = new MarkdownString(body);
    this.body.isTrusted = true;
  }

  private generatePreviewContent(content: string) {
    return content
      .replace(SHELL_SCRIPT_PATTERN, (_, script) => {
        const args = encodeURIComponent(JSON.stringify([script]));
        return `> [${script}](command:codetour.sendTextToTerminal?${args} "Run \\"${script}\\" in a terminal")`;
      })
      .replace(COMMAND_PATTERN, (_, commandPrefix, params) => {
        const args = encodeURIComponent(JSON.stringify(JSON.parse(params)));
        return `${commandPrefix}${args}`;
      })
      .replace(
        TOUR_REFERENCE_PATTERN,
        (_, linkTitle, tourTitle, stepNumber) => {
          if (!tourTitle) {
            const title = linkTitle || `#${stepNumber}`;
            return `[${title}](command:codetour.navigateToStep?${stepNumber} "Navigate to step #${stepNumber}")`;
          }

          const tours = store.activeTour?.tours || store.tours;
          const tour = tours.find(tour => tour.title === tourTitle);
          if (tour) {
            const args = [tourTitle];

            if (stepNumber) {
              args.push(Number(stepNumber));
            }
            const argsContent = encodeURIComponent(JSON.stringify(args));
            const title = linkTitle || tourTitle;
            return `[${title}](command:codetour.startTourByTitle?${argsContent} "Start \\"#${tourTitle}\\" tour")`;
          }

          return _;
        }
      );
  }
}

let controller: CommentController | null;

export async function focusPlayer() {
  const currentThread = store.activeTour!.thread!;
  showDocument(currentThread.uri, currentThread.range);
}

export async function startPlayer() {
  if (controller) {
    controller.dispose();
  }

  controller = comments.createCommentController(
    CONTROLLER_ID,
    CONTROLLER_LABEL
  );

  // TODO: Correctly limit the commenting ranges
  // to files within the workspace root
  controller.commentingRangeProvider = {
    provideCommentingRanges: (document: TextDocument) => {
      if (store.isRecording) {
        return [new Range(0, 0, document.lineCount, 0)];
      } else {
        return null;
      }
    }
  };
}

export async function stopPlayer() {
  if (store.activeTour?.thread) {
    store.activeTour!.thread.dispose();
    store.activeTour!.thread = null;
  }

  if (controller) {
    controller.dispose();
    controller = null;
  }
}

const VIEW_COMMANDS = new Map([
  ["comments", "workbench.panel.comments"],
  ["console", "workbench.panel.console"],
  ["debug", "workbench.view.debug"],
  ["debug:breakpoints", "workbench.debug.action.focusBreakpointsView"],
  ["debug:callstack", "workbench.debug.action.focusCallStackView"],
  ["debug:variables", "workbench.debug.action.focusVariablesView"],
  ["debug:watch", "workbench.debug.action.focusWatchView"],
  ["explorer", "workbench.view.explorer"],
  ["extensions", "workbench.view.extensions"],
  ["extensions:disabled", "extensions.disabledExtensionList.focus"],
  ["extensions:enabled", "extensions.enabledExtensionList.focus"],
  ["output", "workbench.panel.output"],
  ["problems", "workbench.panel.markers"],
  ["scm", "workbench.view.scm"],
  ["search", "workbench.view.search"],
  ["terminal", "workbench.panel.terminal"]
]);

async function renderCurrentStep() {
  if (store.activeTour!.thread) {
    store.activeTour!.thread.dispose();
  }

  const currentTour = store.activeTour!.tour;
  const currentStep = store.activeTour!.step;

  const step = currentTour!.steps[currentStep];

  if (!step) {
    return;
  }

  // Adjust the line number, to allow the user to specify
  // them in 1-based format, not 0-based
  const line = step.line
    ? step.line - 1
    : step.selection
    ? step.selection.end.line - 1
    : 2000;

  const range = new Range(line, 0, line, 0);
  let label = `Step #${currentStep + 1} of ${currentTour!.steps.length}`;

  if (currentTour.title) {
    label += ` (${currentTour.title})`;
  }

  const workspaceRoot = store.activeTour?.workspaceRoot;
  const uri = await getStepFileUri(step, workspaceRoot, currentTour.ref);
  store.activeTour!.thread = controller!.createCommentThread(uri, range, []);

  const mode = store.isRecording ? CommentMode.Editing : CommentMode.Preview;
  const comment = new CodeTourComment(
    step.description,
    label,
    store.activeTour!.thread!,
    mode
  );

  store.activeTour!.thread.comments = [comment];

  const contextValues = [];
  if (currentStep > 0) {
    contextValues.push("hasPrevious");
  }

  if (currentStep < currentTour.steps.length - 1) {
    contextValues.push("hasNext");
  }

  store.activeTour!.thread.contextValue = contextValues.join(".");
  store.activeTour!.thread.collapsibleState =
    CommentThreadCollapsibleState.Expanded;

  let selection;
  if (step.selection) {
    // Adjust the 1-based positions
    // to the 0-based positions that
    // VS Code's editor uses.
    selection = new Selection(
      step.selection.start.line - 1,
      step.selection.start.character - 1,
      step.selection.end.line - 1,
      step.selection.end.character - 1
    );
  } else {
    selection = new Selection(range.start, range.end);
  }

  await showDocument(uri, range, selection);

  if (step.directory) {
    const directoryUri = getFileUri(step.directory, workspaceRoot);
    commands.executeCommand("revealInExplorer", directoryUri);
  } else if (step.view) {
    const commandName = VIEW_COMMANDS.has(step.view)
      ? VIEW_COMMANDS.get(step.view)!
      : `${step.view}.focus`;

    try {
      await commands.executeCommand(commandName);
    } catch {
      window.showErrorMessage(
        `The current tour step is attempting to focus a view which isn't available: ${step.view}. Please check the tour and try again.`
      );
    }
  }

  if (step.commands) {
    step.commands.forEach(async command => {
      let name = command,
        args: any[] = [];

      if (command.includes("?")) {
        const parts = command.split("?");
        name = parts[0];
        args = JSON.parse(parts[1]);
      }

      try {
        await commands.executeCommand(name, ...args);
      } catch {
        // Silently fail, since it's unclear if the
        // command was critical to the step or not.
      }
    });
  }
}

async function showDocument(uri: Uri, range: Range, selection?: Selection) {
  const document =
    window.visibleTextEditors.find(
      editor => editor.document.uri.toString() === uri.toString()
    ) || (await window.showTextDocument(uri, { preserveFocus: true }));

  // TODO: Figure out how to force focus when navigating
  // to documents which are already open.

  if (selection) {
    document.selection = selection;
  }

  document.revealRange(range, TextEditorRevealType.InCenter);
}

// Watch for changes to the active tour property,
// and automatically re-render the current step in response.
reaction(
  () => [
    store.activeTour
      ? [
          store.activeTour.step,
          store.activeTour.tour.title,
          store.activeTour.tour.steps.map(step => [
            step.title,
            step.description,
            step.line,
            step.directory,
            step.view
          ])
        ]
      : null
  ],
  () => {
    if (store.activeTour) {
      renderCurrentStep();
    }
  }
);

{'repo_name': 'vsls-contrib/codetour', 'stars': '970', 'repo_language': 'TypeScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -6427104926458056869, 'source_dataset': 'data'}


query emailTemplates(
  $shopId: ID!,
  $first: ConnectionLimitInt,
  $last:  ConnectionLimitInt,
  $before: ConnectionCursor,
  $after: ConnectionCursor,
  $offset: Int
) {
  emailTemplates(
    shopId: $shopId,
    first: $first,
    last: $last,
    before: $before,
    after: $after,
    offset: $offset
  ) {
		nodes {
      _id
      name
      title
      subject
      template
      shopId
    }
  }
}

{'repo_name': 'reactioncommerce/reaction', 'stars': '10392', 'repo_language': 'JavaScript', 'file_name': 'relay_connection_arguments_spec_custom.cjs', 'mime_type': 'text/plain', 'hash': -1477644136775915294, 'source_dataset': 'data'}


// 在前面的例子中，我们用 [互斥锁](mutexes) 进行了明确的锁定，
// 来让共享的 state 跨多个 Go 协程同步访问。
// 另一个选择是，使用内建协程和通道的同步特性来达到同样的效果。
// Go 共享内存的思想是，通过通信使每个数据仅被单个协程所拥有，即通过通信实现共享内存。
// 基于通道的方法与该思想完全一致！

package main

import (
	"fmt"
	"math/rand"
	"sync/atomic"
	"time"
)

// 在这个例子中，state 将被一个单独的协程拥有。
// 这能保证数据在并行读取时不会混乱。
// 为了对 state 进行读取或者写入，
// 其它的协程将发送一条数据到目前拥有数据的协程中，
// 然后等待接收对应的回复。
// 结构体 `readOp` 和 `writeOp` 封装了这些请求，并提供了响应协程的方法。
type readOp struct {
	key  int
	resp chan int
}
type writeOp struct {
	key  int
	val  int
	resp chan bool
}

func main() {

	// 和前面的例子一样，我们会计算操作执行的次数。
	var readOps uint64
	var writeOps uint64

	// 其他协程将通过 `reads` 和 `writes` 通道来发布 `读` 和 `写` 请求。
	reads := make(chan readOp)
	writes := make(chan writeOp)

	// 这就是拥有 `state` 的那个协程，
	// 和前面例子中的 map 一样，不过这里的 state 是被这个状态协程私有的。
	// 这个协程不断地在 `reads` 和 `writes` 通道上进行选择，并在请求到达时做出响应。
	// 首先，执行请求的操作；然后，执行响应，在响应通道 `resp` 上发送一个值，表明请求成功（`reads` 的值则为 state 对应的值）。
	go func() {
		var state = make(map[int]int)
		for {
			select {
			case read := <-reads:
				read.resp <- state[read.key]
			case write := <-writes:
				state[write.key] = write.val
				write.resp <- true
			}
		}
	}()

	// 启动 100 个协程通过 `reads` 通道向拥有 state 的协程发起读取请求。
	// 每个读取请求需要构造一个 `readOp`，发送它到 `reads` 通道中，
	// 并通过给定的 `resp` 通道接收结果。
	for r := 0; r < 100; r++ {
		go func() {
			for {
				read := readOp{
					key:  rand.Intn(5),
					resp: make(chan int)}
				reads <- read
				<-read.resp
				atomic.AddUint64(&readOps, 1)
				time.Sleep(time.Millisecond)
			}
		}()
	}

	// 用相同的方法启动 10 个写操作。
	for w := 0; w < 10; w++ {
		go func() {
			for {
				write := writeOp{
					key:  rand.Intn(5),
					val:  rand.Intn(100),
					resp: make(chan bool)}
				writes <- write
				<-write.resp
				atomic.AddUint64(&writeOps, 1)
				time.Sleep(time.Millisecond)
			}
		}()
	}

	// 让协程们跑 1s。
	time.Sleep(time.Second)

	// 最后，获取并报告 `ops` 值。
	readOpsFinal := atomic.LoadUint64(&readOps)
	fmt.Println("readOps:", readOpsFinal)
	writeOpsFinal := atomic.LoadUint64(&writeOps)
	fmt.Println("writeOps:", writeOpsFinal)
}

{'repo_name': 'gobyexample-cn/gobyexample', 'stars': '824', 'repo_language': 'Go', 'file_name': 'closures.hash', 'mime_type': 'text/plain', 'hash': 1218151969099242104, 'source_dataset': 'data'}


# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the gRPC route guide client."""

from __future__ import print_function

import random
import os
import grpc

# Recommend to the directory structure of client.runfiles to figure out the
# correct import here.
from example.proto import routeguide_pb2
from example.proto import routeguide_pb2_grpc

import resources

def make_route_note(message, latitude, longitude):
    return routeguide_pb2.RouteNote(
        message=message,
        location=routeguide_pb2.Point(latitude=latitude, longitude=longitude))

def guide_get_one_feature(stub, point):
    feature = stub.GetFeature(point)
    if not feature.location:
        print("Server returned incomplete feature")
        return

    if feature.name:
        print("Feature called %s at %s" % (feature.name, feature.location))
    else:
        print("Found no feature at %s" % feature.location)

def guide_get_feature(stub):
    guide_get_one_feature(stub,
                          routeguide_pb2.Point(
                              latitude=409146138, longitude=-746188906))
    guide_get_one_feature(stub, routeguide_pb2.Point(latitude=0, longitude=0))

def guide_list_features(stub):
    rectangle = routeguide_pb2.Rectangle(
        lo=routeguide_pb2.Point(latitude=400000000, longitude=-750000000),
        hi=routeguide_pb2.Point(latitude=420000000, longitude=-730000000))
    print("Looking for features between 40, -75 and 42, -73")

    features = stub.ListFeatures(rectangle)

    for feature in features:
        print("Feature called %s at %s" % (feature.name, feature.location))

def generate_route(feature_list):
    for _ in range(0, 10):
        random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
        print("Visiting point %s" % random_feature.location)
        yield random_feature.location

def guide_record_route(stub):
    feature_list = resources.read_route_guide_database()

    route_iterator = generate_route(feature_list)
    route_summary = stub.RecordRoute(route_iterator)
    print("Finished trip with %s points " % route_summary.point_count)
    print("Passed %s features " % route_summary.feature_count)
    print("Travelled %s meters " % route_summary.distance)
    print("It took %s seconds " % route_summary.elapsed_time)

def generate_messages():
    messages = [
        make_route_note("First message", 0, 0),
        make_route_note("Second message", 0, 1),
        make_route_note("Third message", 1, 0),
        make_route_note("Fourth message", 0, 0),
        make_route_note("Fifth message", 1, 0),
    ]
    for msg in messages:
        print("Sending %s at %s" % (msg.message, msg.location))
        yield msg

def guide_route_chat(stub):
    responses = stub.RouteChat(generate_messages())
    for response in responses:
        print("Received message %s at %s" % (response.message,
                                             response.location))

def run():
    # NOTE(gRPC Python Team): .close() is possible on a channel and should be
    # used in circumstances in which the with statement does not fit the needs
    # of the code.
    port = '50051'
    if os.environ.get("SERVER_PORT"):
        port = os.environ.get("SERVER_PORT")

    with grpc.insecure_channel('localhost:'+port) as channel:
        stub = routeguide_pb2_grpc.RouteGuideStub(channel)
        print("-------------- GetFeature --------------")
        guide_get_feature(stub)
        print("-------------- ListFeatures --------------")
        guide_list_features(stub)
        print("-------------- RecordRoute --------------")
        guide_record_route(stub)
        print("-------------- RouteChat --------------")
        guide_route_chat(stub)

if __name__ == '__main__':
    run()

{'repo_name': 'stackb/rules_proto', 'stars': '167', 'repo_language': 'Starlark', 'file_name': 'presubmit.yml', 'mime_type': 'text/plain', 'hash': -6989282753130449347, 'source_dataset': 'data'}


# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may
# not use this file except in compliance with the License. You may
# obtain a copy of the License at
# https://opensource.org/licenses/BSD-3-Clause
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
# See the AUTHORS file for names of contributors.

import unittest

import sys
import torch
import turbo_transformers
from transformers.modeling_bert import BertConfig, BertIntermediate
import numpy
import os

sys.path.append(os.path.dirname(__file__))
import test_helper

def create_test(batch_size, seq_length):
    class TestBertIntermediate(unittest.TestCase):
        def init_data(self, use_cuda: bool) -> None:
            self.test_device = torch.device('cuda:0') if use_cuda else \
                torch.device('cpu:0')
            if not use_cuda:
                torch.set_num_threads(4)
                turbo_transformers.set_num_threads(4)

            torch.set_grad_enabled(False)
            self.cfg = BertConfig()

            self.torch_intermediate = BertIntermediate(self.cfg)
            if torch.cuda.is_available():
                self.torch_intermediate.to(self.test_device)
            self.torch_intermediate.eval()

            self.turbo_intermediate = turbo_transformers.BertIntermediate.from_torch(
                self.torch_intermediate)

        def check_torch_and_turbo(self, use_cuda):
            self.init_data(use_cuda=use_cuda)
            device = "GPU" if use_cuda else "CPU"
            num_iter = 2
            hidden_size = self.cfg.hidden_size
            input_tensor = torch.rand(size=(batch_size, seq_length,
                                            hidden_size),
                                      dtype=torch.float32,
                                      device=self.test_device)

            turbo_model = lambda: self.turbo_intermediate(input_tensor)
            turbo_result, turbo_qps, turbo_time = \
                test_helper.run_model(turbo_model, use_cuda, num_iter)

            print(
                f"BertIntermediate \"({batch_size},{seq_length:03})\" ",
                f"{device} TurboTransform QPS,  {turbo_qps}, time, {turbo_time}"
            )

            torch_model = lambda: self.torch_intermediate(input_tensor)
            torch_result, torch_qps, torch_time = \
                test_helper.run_model(torch_model, use_cuda, num_iter)

            print(f"BertIntermediate \"({batch_size},{seq_length:03})\" ",
                  f"{device} Torch QPS,  {torch_qps}, time, {torch_time}")

            torch_result = torch_result.cpu().numpy()
            turbo_result = turbo_result.cpu().numpy()

            self.assertTrue(
                numpy.allclose(torch_result,
                               turbo_result,
                               rtol=1e-4,
                               atol=1e-3))

            with open("bert_intermediate_res.txt", "a") as fh:
                fh.write(
                    f"\"({batch_size},{seq_length:03})\", {torch_qps}, {turbo_qps}\n"
                )

        def test_intermediate(self):
            self.check_torch_and_turbo(use_cuda=False)
            if torch.cuda.is_available() and \
                turbo_transformers.config.is_compiled_with_cuda():
                self.check_torch_and_turbo(use_cuda=True)

    globals()[f"TestBertIntermediate_{batch_size}_{seq_length:03}"] = \
        TestBertIntermediate

with open("bert_intermediate_res.txt", "w") as fh:
    fh.write(", torch, turbo_transformers\n")
for batch_size in [1, 2]:
    for seq_length in [10, 16, 20, 24, 40, 48, 60, 64, 80, 100, 120, 128]:
        create_test(batch_size, seq_length)

if __name__ == '__main__':
    unittest.main()

{'repo_name': 'Tencent/TurboTransformers', 'stars': '392', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -859165108716473986, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace SCJMapper_V2.Layout
{
  /// <summary>
  /// Reads a DeviceFile from a file or stream
  /// </summary>
  class ControllerJson
  {

    /// <summary>
    /// Reads from a file one Controller entry
    /// </summary>
    /// <param name="jFilename">The Json Filename</param>
    /// <returns>A Controller obj or null for errors</returns>
    public static DeviceFile FromJson( string jFilename )
    {
      DeviceFile c = null;
      string fn = jFilename;
      if ( !File.Exists( jFilename ) ) {
        fn = Path.Combine( TheUser.LayoutsDir, fn ); // if it is not found use the default path
      }
      if ( File.Exists( fn ) ) {
        using ( var ts = File.OpenRead( fn ) ) {
          c = FromJson( ts );
        }
      }
      return c;
    }

    /// <summary>
    /// Reads from the open stream one Controller entry
    /// </summary>
    /// <param name="jStream">An open stream at position</param>
    /// <returns>A Controller obj or null for errors</returns>
    public static DeviceFile FromJson( Stream jStream )
    {
      try {
        var jsonSerializer = new DataContractJsonSerializer( typeof( DeviceFile ) );
        object objResponse = jsonSerializer.ReadObject( jStream );
        var jsonResults = objResponse as DeviceFile;
        return jsonResults;
      }
#pragma warning disable CS0168 // Variable is declared but never used
      catch ( Exception e ) {
#pragma warning restore CS0168 // Variable is declared but never used
        return null;
      }
    }

  }
}

{'repo_name': 'SCToolsfactory/SCJMapper-V2', 'stars': '110', 'repo_language': 'C#', 'file_name': 'ActionMapsCls.cs', 'mime_type': 'text/plain', 'hash': 2808358463540093247, 'source_dataset': 'data'}


#region License
/* **********************************************************************************
 * Copyright (c) Roman Ivantsov
 * This source code is subject to terms and conditions of the MIT License
 * for Irony. A copy of the license can be found in the License.txt file
 * at the root of this distribution.
 * By using this source code in any fashion, you are agreeing to be bound by the terms of the
 * MIT License.
 * You must not remove this notice from this software.
 * **********************************************************************************/
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Security;
using Irony.Parsing;
using Irony.Interpreter.Ast;

namespace Irony.Interpreter {

  public enum AppStatus {
    Ready,
    Evaluating,
    WaitingMoreInput, //command line only
    SyntaxError,
    RuntimeError,
    Crash, //interpreter crash
    Aborted
  }

  /// <summary> Represents a running instance of a script application.  </summary>
  public sealed class ScriptApp {
    public readonly LanguageData Language;
    public readonly LanguageRuntime Runtime;
    public Parser Parser { get; private set; }

    public AppDataMap DataMap;

    public Scope[] StaticScopes;
    public Scope MainScope;
    public IDictionary<string, object> Globals {get; private set;}
    private IList<Assembly> ImportedAssemblies = new List<Assembly>();

    public IConsoleAdapter Console = new BufferedConsoleAdapter();

    // Current mode/status variables
    public AppStatus Status;
    public long EvaluationTime;
    public Exception LastException;
    public bool RethrowExceptions = true;

    public ParseTree LastScript { get; private set; } //the root node of the last executed script

    #region Constructors
    public ScriptApp(LanguageData language) {
      Language = language;
      var grammar = language.Grammar as InterpretedLanguageGrammar;
      Runtime = grammar.CreateRuntime(language);
      DataMap = new AppDataMap(Language.Grammar.CaseSensitive);
      Init();
    }

    public ScriptApp(LanguageRuntime runtime)  {
      Runtime = runtime;
      Language = Runtime.Language;
      DataMap = new AppDataMap(Language.Grammar.CaseSensitive);
      Init();
    }

    public ScriptApp(AppDataMap dataMap) {
      DataMap = dataMap;
      Init();
    }

    [SecuritySafeCritical]
    private void Init() {
      Parser = new Parser(Language);
      //Create static scopes
      MainScope = new Scope(DataMap.MainModule.ScopeInfo, null, null, null);
      StaticScopes = new Scope[DataMap.StaticScopeInfos.Count];
      StaticScopes[0] = MainScope;
      Globals = MainScope.AsDictionary();
    }

    #endregion

    public LogMessageList GetParserMessages() {
      return Parser.Context.CurrentParseTree.ParserMessages;
    }
    // Utilities
    public IEnumerable<Assembly> GetImportAssemblies() {
      //simple default case - return all assemblies loaded in domain
      return AppDomain.CurrentDomain.GetAssemblies();
    }

    public ParseMode ParserMode {
      get { return Parser.Context.Mode; }
      set { Parser.Context.Mode = value; }
    }

    #region Evaluation
    public object Evaluate(string script) {
      try {
        var parsedScript = Parser.Parse(script);
        if (parsedScript.HasErrors()) {
          Status = AppStatus.SyntaxError;
          if (RethrowExceptions)
            throw new ScriptException("Syntax errors found.");
          return null;
        }

        if (ParserMode == ParseMode.CommandLine && Parser.Context.Status == ParserStatus.AcceptedPartial) {
          Status = AppStatus.WaitingMoreInput;
          return null;
        }
        LastScript = parsedScript;
        var result = EvaluateParsedScript();
        return result;
      } catch (ScriptException) {
        throw;
      } catch (Exception ex) {
        this.LastException = ex;
        this.Status = AppStatus.Crash;
        return null;
      }
    }

    // Irony interpreter requires that once a script is executed in a ScriptApp, it is bound to AppDataMap object,
    // and all later script executions should be performed only in the context of the same app (or at least by an App with the same DataMap).
    // The reason is because the first execution sets up a data-binding fields, like slots, scopes, etc, which are bound to ScopeInfo objects,
    // which in turn is part of DataMap.
    public object Evaluate(ParseTree parsedScript) {
      Util.Check (parsedScript.Root.AstNode != null,  "Root AST node is null, cannot evaluate script. Create AST tree first.");
      var root = parsedScript.Root.AstNode as AstNode;
      Util.Check(root != null,
        "Root AST node {0} is not a subclass of Irony.Interpreter.AstNode. ScriptApp cannot evaluate this script.", root.GetType());
      Util.Check (root.Parent == null || root.Parent == DataMap.ProgramRoot,
        "Cannot evaluate parsed script. It had been already evaluated in a different application.");
      LastScript = parsedScript;
      return EvaluateParsedScript();
    }

    public object Evaluate() {
      Util.Check (LastScript != null, "No previously parsed/evaluated script.");
      return EvaluateParsedScript();
    }

    //Actual implementation
    private object EvaluateParsedScript() {
      LastScript.Tag = DataMap;
      var root = LastScript.Root.AstNode as AstNode;
      root.DependentScopeInfo = MainScope.Info;

      Status = AppStatus.Evaluating;
      ScriptThread thread = null;
      try {
        thread = new ScriptThread(this);
        var result = root.Evaluate(thread);
        if (result != null)
          thread.App.WriteLine(result.ToString());
        Status = AppStatus.Ready;
        return result;
      } catch (ScriptException se) {
        Status = AppStatus.RuntimeError;
        se.Location = thread.CurrentNode.Location;
        se.ScriptStackTrace = thread.GetStackTrace();
        LastException = se;
        if (RethrowExceptions)
          throw;
        return null;
      } catch (Exception ex) {
        Status = AppStatus.RuntimeError;
        var se = new ScriptException(ex.Message, ex, thread.CurrentNode.Location, thread.GetStackTrace());
        LastException = se;
        if (RethrowExceptions)
          throw se;
        return null;

      }//catch

    }
    #endregion

    #region Output writing

    #region ConsoleWrite event
    public event EventHandler<ConsoleWriteEventArgs> ConsoleWrite;
    private void OnConsoleWrite(string text) {
      if (ConsoleWrite != null) {
        ConsoleWriteEventArgs args = new ConsoleWriteEventArgs(text);
        ConsoleWrite(this, args);
      }
    }
    #endregion

    public void Write(string text) {
      OnConsoleWrite(text);
      Console?.Write(text);
    }

    public void WriteLine(string text) {
      OnConsoleWrite(text + Environment.NewLine);
      Console?.WriteLine(text);
    }

    public void ClearOutputBuffer() {
      Console?.Clear();
    }

    public string GetOutput() {
      return Console?.GetOutput();
    }

    #endregion

  }//class
}

{'repo_name': 'IronyProject/Irony', 'stars': '265', 'repo_language': 'C#', 'file_name': 'LanguageRuntime_OpDispatch.cs', 'mime_type': 'text/plain', 'hash': 6079159163705181456, 'source_dataset': 'data'}


/*
 This file is part of Darling.

 Copyright (C) 2017 Lubos Dolezel

 Darling is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 Darling is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with Darling.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Contacts/CNContactsLoggerProvider.h>

@implementation CNContactsLoggerProvider

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    return [NSMethodSignature signatureWithObjCTypes: "v@:"];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"Stub called: %@ in %@", NSStringFromSelector([anInvocation selector]), [self class]);
}

@end

{'repo_name': 'darlinghq/darling', 'stars': '5627', 'repo_language': 'C', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 7147881421805077449, 'source_dataset': 'data'}


// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S15.2.2.1_A1_T2;
* @section: 15.2.2.1;
* @assertion: When the Object constructor is called with no arguments the following steps are taken:
* (The argument value was not supplied or its type was Null or Undefined.)
*   i)	Create a new native ECMAScript object.
*  ii) 	The [[Prototype]] property of the newly constructed object is set to the Object prototype object.
* iii) 	The [[Class]] property of the newly constructed object is set to "Object".
*  iv) 	The newly constructed object has no [[Value]] property.
*   v) 	Return the newly created native object;
* @description: Creating new Object(void 0) and checking its properties;
*/

//var foo = void 0;
var obj = new Object(void 0);

// CHECK#0
if (obj === undefined) {
  $ERROR('#0: new Object(undefined) return the newly created native object.');
}

// CHECK#1
if (obj.constructor !== Object) {
  $ERROR('#1: new Object(undefined) create a new native ECMAScript object');
}

// CHECK#2
if (!(Object.prototype.isPrototypeOf(obj))) {
  $ERROR('#2: when new Object(undefined) calls the [[Prototype]] property of the newly constructed object is set to the Object prototype object.');
}

// CHECK#3
to_string_result = '[object '+ 'Object' +']';
if (obj.toString() !== to_string_result) {
  $ERROR('#3: when new Object(undefined) calls the [[Class]] property of the newly constructed object is set to "Object".');
}

// CHECK#4
if (obj.valueOf().toString() !== to_string_result.toString()) {
  $ERROR('#4: when new Object(undefined) calls the newly constructed object has no [[Value]] property.');
}

{'repo_name': 'fholm/IronJS', 'stars': '649', 'repo_language': 'JavaScript', 'file_name': '0.1.94.txt', 'mime_type': 'text/plain', 'hash': 3854983402071766154, 'source_dataset': 'data'}


CtrlF.sikuli\AtomIsOpen.sikuli
 (Download this script)

kol = 0
while True:
    FindIm = findAll()
    ArrOfImage = list(FindIm)
    KolImages  = len(ArrOfImage)
    print 'KolImages='+ str(KolImages)
    for n in range(0, KolImages):
        t = ArrOfImage[n]
        print 't.x='+ str(t.x)
    if KolImages > 0:
        t = ArrOfImage[KolImages-1]
        print 'click t.x='+ str(t.x)
        click(Location(t.x+5,t.y+5))
        break
    sleep(1)
    kol = kol+1
    if kol > 5:
        exit(1)

exit(0)

{'repo_name': 'vanessa-opensource/add', 'stars': '186', 'repo_language': '1C Enterprise', 'file_name': 'ObjectModule.bsl', 'mime_type': 'text/plain', 'hash': -2903021087479647577, 'source_dataset': 'data'}


<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     rwd_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>

<?php $_shipment = $this->getShipment() ?>
<?php $_order    = $this->getOrder() ?>

<?php if ($_shipment && $_order): ?>

    <?php $_items     = $_order->getAllItems() ?>
    <?php $_itemCount = count($_items) ?>

                <?php if($_itemCount > 1): echo $this->__('Items in your order'); else: echo $this->__('Item in your order'); endif; ?>

                <?php echo $this->__('Sku'); ?>

                <?php echo $this->__('Qty'); ?>

        <?php $i=0; foreach ($_shipment->getAllItems() as $_item): ?>
        <?php if($_item->getOrderItem()->getParentItem()) continue; else $i++; ?>
            <?php echo $this->getItemHtml($_item) ?>
        <?php endforeach; ?>

<?php endif; ?>

{'repo_name': 'OpenMage/magento-lts', 'stars': '496', 'repo_language': 'PHP', 'file_name': 'iestyles.css', 'mime_type': 'text/plain', 'hash': -6110366589517772440, 'source_dataset': 'data'}


--- ../src-base/minecraft/net/minecraft/block/BlockSlab.java
+++ ../src-work/minecraft/net/minecraft/block/BlockSlab.java
@@ -21,7 +21,7 @@

 public abstract class BlockSlab extends Block
 {
-    public static final PropertyEnum<BlockSlab.EnumBlockHalf> HALF = PropertyEnum.<BlockSlab.EnumBlockHalf>create("half", BlockSlab.EnumBlockHalf.class);
+    public static final PropertyEnum<EnumBlockHalf> HALF = PropertyEnum.<EnumBlockHalf>create("half", EnumBlockHalf.class);
     protected static final AxisAlignedBB AABB_BOTTOM_HALF = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5D, 1.0D);
     protected static final AxisAlignedBB AABB_TOP_HALF = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 1.0D, 1.0D, 1.0D);

@@ -50,13 +50,13 @@
         }
         else
         {
-            return state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP ? AABB_TOP_HALF : AABB_BOTTOM_HALF;
+            return state.getValue(HALF) == EnumBlockHalf.TOP ? AABB_TOP_HALF : AABB_BOTTOM_HALF;
         }
     }

     public boolean isTopSolid(IBlockState state)
     {
-        return ((BlockSlab)state.getBlock()).isDouble() || state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP;
+        return ((BlockSlab)state.getBlock()).isDouble() || state.getValue(HALF) == EnumBlockHalf.TOP;
     }

     public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face)
@@ -65,13 +65,13 @@
         {
             return BlockFaceShape.SOLID;
         }
-        else if (face == EnumFacing.UP && state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP)
+        else if (face == EnumFacing.UP && state.getValue(HALF) == EnumBlockHalf.TOP)
         {
             return BlockFaceShape.SOLID;
         }
         else
         {
-            return face == EnumFacing.DOWN && state.getValue(HALF) == BlockSlab.EnumBlockHalf.BOTTOM ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED;
+            return face == EnumFacing.DOWN && state.getValue(HALF) == EnumBlockHalf.BOTTOM ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED;
         }
     }

@@ -80,9 +80,22 @@
         return this.isDouble();
     }

+    @Override
+    public boolean doesSideBlockRendering(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing face)
+    {
+        if (net.minecraftforge.common.ForgeModContainer.disableStairSlabCulling)
+            return super.doesSideBlockRendering(state, world, pos, face);
+
+        if ( state.isOpaqueCube() )
+            return true;
+
+        EnumBlockHalf side = state.getValue(HALF);
+        return (side == EnumBlockHalf.TOP && face == EnumFacing.UP) || (side == EnumBlockHalf.BOTTOM && face == EnumFacing.DOWN);
+    }
+
     public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
     {
-        IBlockState iblockstate = super.getStateForPlacement(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM);
+        IBlockState iblockstate = super.getStateForPlacement(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(HALF, EnumBlockHalf.BOTTOM);

         if (this.isDouble())
         {
@@ -90,7 +103,7 @@
         }
         else
         {
-            return facing != EnumFacing.DOWN && (facing == EnumFacing.UP || (double)hitY <= 0.5D) ? iblockstate : iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.TOP);
+            return facing != EnumFacing.DOWN && (facing == EnumFacing.UP || (double)hitY <= 0.5D) ? iblockstate : iblockstate.withProperty(HALF, EnumBlockHalf.TOP);
         }
     }

@@ -115,11 +128,11 @@
         {
             return false;
         }
-        else
+        else if (false) // Forge: Additional logic breaks doesSideBlockRendering and is no longer useful.
         {
             IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side));
-            boolean flag = isHalfSlab(iblockstate) && iblockstate.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP;
-            boolean flag1 = isHalfSlab(blockState) && blockState.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP;
+            boolean flag = isHalfSlab(iblockstate) && iblockstate.getValue(HALF) == EnumBlockHalf.TOP;
+            boolean flag1 = isHalfSlab(blockState) && blockState.getValue(HALF) == EnumBlockHalf.TOP;

             if (flag1)
             {
@@ -149,6 +162,7 @@
                 return !isHalfSlab(iblockstate) || flag;
             }
         }
+        return super.shouldSideBeRendered(blockState, blockAccess, pos, side);
     }

     @SideOnly(Side.CLIENT)

{'repo_name': 'Luohuayu/CatServer', 'stars': '274', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': -1740226123435231044, 'source_dataset': 'data'}


import { SignedZeroExTransaction } from '@0x/types';
import { BigNumber } from '@0x/utils';

export interface CoordinatorApproval {
    transaction: SignedZeroExTransaction;
    txOrigin: string;
}

export interface SignedCoordinatorApproval extends CoordinatorApproval {
    signature: string;
}

export interface CoordinatorTransaction {
    salt: BigNumber;
    signerAddress: string;
    data: string;
}

{'repo_name': '0xProject/0x-monorepo', 'stars': '1233', 'repo_language': 'TypeScript', 'file_name': 'test.pyi', 'mime_type': 'text/x-python', 'hash': 1535423376526551630, 'source_dataset': 'data'}


# coding=utf-8
"""Unicode glyphs that resemble other glyphs."""
import random
import string

alternates = {
    "a" : u"",
    "b" : u"",
    "c" : u"ϲᒼᑦсϚⅽ꜀꜂ℂ℃⊏",
    "d" : u"",
    "e" : u"💶ᥱ",
    "f" : u"ſʄ",
    "g" : u"",
    "h" : u"ℌᑋ",
    "i" : u"",
    "j" : u"",
    "k" : u"ⱪ",
    "l" : u"",
    "m" : u"ϻ⩋ᨓოጦጠᶬ₥ෆ",
    "n" : u"⩏സﬨヘ",
    "o" : u"",
    "p" : u"ᕵᑭᑭⲢ",
    "q" : u"",
    "r" : u"╭┌ɼᒋᒥ꜒Γᖋ┍ᒋℾᒋɼґᣘ𝝘ⲅ𝈬꜓⦧",
    "s" : u"",
    "t" : u"†Ϯϯ┼┽┿╀⍭┾╇+ⵜ╁╪╈╅╅╆╄⨨╂╃╉╊╋╉ߙ⁺ᚐႵ⍖Էէヒナヒモ",
    "u" : u"Цυսᥙɥᐡ",
    "v" : u"",
    "w" : u"ᐜ",
    "x" : u"☒",
    "y" : u"ʮկ",
    "z" : u"",

    "A" : u"⍍ᐃ",
    "B" : u"β3",
    "C" : u"ᑕϹСʗⅭⵎᥴⲤƇᑕ",
    "D" : u"ᐅᑓᑔ",
    "E" : u"⪡ΕꗋΕƐЄᎬⴹЕĘɛℇᙓミ",
    "F" : u"ҒϜғƑߓ𝟋₣ᖴ╒𐌅℉",
    "G" : u"",
    "H" : u"╫⩆",
    "I" : u"エェヱ",
    "J" : u"",
    "K" : u"ΚƘKК𐌊ҚкⱩⲔκᏦϏҜ𝝟₭ꗪ",
    "L" : u"レ",
    "M" : u"ΜМϺ𐌑ⅯмⱮӍ𝝡ӎ",
    "N" : u"₪Иⵍи",
    "O" : u"🝕▣⌻⏣⧈0ロ",
    "P" : u"ꝒР♇ҏРΡᏢ⛿ᕈ𐌛Ᵽ𐌓ǷⲢ℗アァ",
    "Q" : u"",
    "R" : u"𝈖ᎡƦɌⴽᖇ",
    "S" : u"⑀",
    "T" : u"⊤┬ΤТ⟙ꔋ𝖳┰┯т𝍮⫪┮Ƭ🝨⥡┭Ţ⏉ᚁᎢ┳╥𝝩Ꞇィイフヮワᐪ",
    "U" : u"⋃⨆ᑌ∪ՍⵡŲ∐⌴ᓑԱ⊔𝈈பVリᑌ",
    "V" : u"ᐺ",
    "W" : u"",
    "X" : u"⪥",
    "Y" : u"߂ЏЦ💴",
    "Z" : u"",
    "-" : u"ー",
}

multi_character_alternates = {
    "B" : ["]3", "|3"],
    "H" : ["|-|", "|=|"],
    "K" : ["]<", ")<", "|<"],
    "O" : ["()", "[]", "{}"],
    "U" : ["|_|"],
    "V" : ["\/"],
}

from olipy.alphabet import CUSTOM_ALPHABETS

alternate_letterforms = {}
for k, v in alternates.items():
    alternate_letterforms[k] = set(v)
for k, v in multi_character_alternates.items():
    alternate_letterforms[k].update(v)

full_alphabet_mapping = string.ascii_uppercase + string.ascii_lowercase
lowercase_alphabet_mapping = string.ascii_lowercase
def map_alphabet(alphabet, mapping=full_alphabet_mapping):
    for i, char in enumerate(alphabet):
        if not char.strip():
            continue
        map_to = mapping[i]
        alternate_letterforms[map_to].add(char)

# Incorporate some strings that map the alphabet onto alternate 'fonts'.
for alphabet_name in [
        "Completely Circled Alphabetics",
        "Fullwidth Alphabetics" ,
        "Bold Alphabetics" ,
        "Italic Alphabetics" ,
        "Bold Italic Alphabetics" ,
        "Script Alphabetics" ,
        "Script Bold Alphabetics" ,
        "Fraktur Alphabetics" ,
        "Doublestruck Alphabetics" ,
        "Fraktur Bold Alphabetics" ,
        "Sans Alphabetics" ,
        "Sans Bold Alphabetics" ,
        "Sans Italic Alphabetics" ,
        "Sans Bold Italic Alphabetics" ,
        "Monospace Alphabetics" ,
#        "Alphabetics with Umlaut" ,
]:
    alphabet = CUSTOM_ALPHABETS[alphabet_name]
    map_alphabet(alphabet)

full_alphabets = [
    u"ᴬᴮʿᴰᴱ ᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾ ᴿ ᵀᵁⱽᵂ   ₐᵇ ᵈᵉᶠᵍʰᶤʲᵏˡᵐᵑᵒᵖ ʳˢᵗᵤᵛʷˣʸᶻ",
    u"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘ ʀꜱᴛᴜᴠᴡ ʏᴢₐ   ₑ  ₕᵢⱼₖₗₘₙₒₚ ᵣₛₜᵤᵥ ₓ  ",
]
for alphabet in full_alphabets:
    map_alphabet(alphabet)

lowercase_alphabets = [u"⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵"]
for alphabet in lowercase_alphabets:
    map_alphabet(alphabet, lowercase_alphabet_mapping)

# Finally, construct a case-insensitive version of alternate_letterforms.
alternate_letterforms_case_insensitive = dict()
for lower in string.ascii_lowercase:
    upper = lower.upper()
    combined = alternate_letterforms[lower].union(alternate_letterforms[upper])
    for destination in (lower, upper):
        alternate_letterforms_case_insensitive[destination] = combined

def alternate_spelling(string, case_sensitive=False):
    new_string = u""
    if case_sensitive:
        source = alternate_letterforms
    else:
        source = alternate_letterforms_case_insensitive
    for char in string:
        if char in source and source[char]:
            char = random.choice(list(source[char]))
        new_string += char
    return new_string

{'repo_name': 'leonardr/olipy', 'stars': '106', 'repo_language': 'Python', 'file_name': 'apollo_11.json', 'mime_type': 'text/plain', 'hash': 4218300488130717755, 'source_dataset': 'data'}