/* description: Grammar for Slang 1 */

/* lexical grammar */
%lex

DIGIT		      [0-9]
LETTER		      [a-zA-Z]

%%

\s+                                   { /* skip whitespace */ }
"fn"				      { return 'FN'; }
"("                   		      { return 'LPAREN'; }
")"                   		      { return 'RPAREN'; }
"+"                   		      { return 'PLUS'; }
"*"                   		      { return 'TIMES'; }
"add1"                                { return 'ADD1'; }
","                   		      { return 'COMMA'; }
"=>"                   		      { return 'THATRETURNS'; }
<<EOF>>               		      { return 'EOF'; }
{LETTER}({LETTER}|{DIGIT}|_)*  	      { return 'VAR'; }
{DIGIT}+                              { return 'INT'; }
"."                                   { return 'DOT'; }
.                     		      { return 'INVALID'; }

/lex

%start program

%% /* language grammar */

program
    : exp EOF
        { console.log("No syntax errors were detected.\n");
          return createProgram($1);
        }
    ;

exp
    : var_exp  { $$ = $1; }
    | intlit_exp  { $$ = $1; }
    | fn_exp   { $$ = $1; }
    | app_exp  { $$ = $1; }
    | prim_app_exp  { $$ = $1; }
    ;

var_exp
    : VAR  { $$ = createVarExp( $1 ); }
    ;

intlit_exp
    : INT  { $$ = createIntExp( $1 ); }
    ;

fn_exp
    : FN LPAREN formals RPAREN THATRETURNS exp
           { $$ = createFnExp($3,$6); }
    ;

formals
    : /* empty */ { $$ = [ ]; }
    | VAR moreformals
        { var result;
          if ($2 === [ ])
	     result = [ $1 ];
          else {
             $2.unshift($1);
             result = $2;
          }
          $$ = result;
        }
    ;

moreformals
    : /* empty */ { $$ = [ ] }
    | VAR moreformals { $2.unshift($1); $$ = $2; }
    ;

app_exp
    : LPAREN exp args RPAREN
       { $$ = createAppExp($2,$3); }
    ;

prim_app_exp
    : prim_op LPAREN prim_args RPAREN
       { $$ = createPrimAppExp($1,$3); }
    ;

prim_op
    :  PLUS     { $$ = $1; }
    |  TIMES    { $$ = $1; }
    |  ADD1     { $$ = $1; }
    ;

args
    : /* empty */ { $$ = [ ]; }
    | exp args
        { var result;
          if ($2 === [ ])
	     result = [ $1 ];
          else {
             $2.unshift($1);
             result = $2;
          }
          $$ = result;
        }
    ;

prim_args
    :  /* empty */ { $$ = [ ]; }
    |  exp more_prim_args    { $2.unshift($1); $$ = $2; }
    ;

more_prim_args
    : /* empty */ { $$ = [ ] }
    | COMMA exp more_prim_args { $3.unshift($2); $$ = $3; }
    ;

%%


#!/usr/bin/env python3
#
# Copyright 2010-2011 Ettus Research LLC
# Copyright 2018 Ettus Research, a National Instruments Company
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

import usrp2_card_burner #import implementation
try:
    import tkinter, tkinter.filedialog, tkinter.font, tkinter.messagebox
except ImportError:
    import tkFileDialog, tkFont, tkMessageBox
    import Tkinter as tkinter
    tkinter.filedialog = tkFileDialog
    tkinter.font = tkFont
    tkinter.messagebox = tkMessageBox
import os

class BinFileEntry(tkinter.Frame):
    """
    Simple file entry widget for getting the file path of bin files.
    Combines a label, entry, and button with file dialog callback.
    """

    def __init__(self, root, what, def_path=''):
        self._what = what
        tkinter.Frame.__init__(self, root)
        tkinter.Label(self, text=what+":").pack(side=tkinter.LEFT)
        self._entry = tkinter.Entry(self, width=50)
        self._entry.insert(tkinter.END, def_path)
        self._entry.pack(side=tkinter.LEFT)
        tkinter.Button(self, text="...", command=self._button_cb).pack(side=tkinter.LEFT)

    def _button_cb(self):
        filename = tkinter.filedialog.askopenfilename(
            parent=self,
            filetypes=[('bin files', '*.bin'), ('all files', '*.*')],
            title="Select bin file for %s"%self._what,
            initialdir=os.path.dirname(self.get_filename()),
        )

        # open file on your own
        if filename:
            self._entry.delete(0, tkinter.END)
            self._entry.insert(0, filename)

    def get_filename(self):
        return self._entry.get()

class DeviceEntryWidget(tkinter.Frame):
    """
    Simple entry widget for getting the raw device name.
    Combines a label, entry, and helpful text box with hints.
    """

    def __init__(self, root, text=''):
        tkinter.Frame.__init__(self, root)

        tkinter.Button(self, text="Rescan for Devices", command=self._reload_cb).pack()

        self._hints = tkinter.Listbox(self)
        self._hints.bind("<<ListboxSelect>>", self._listbox_cb)
        self._reload_cb()
        self._hints.pack(expand=tkinter.YES, fill=tkinter.X)

        frame = tkinter.Frame(self)
        frame.pack()

        tkinter.Label(frame, text="Raw Device:").pack(side=tkinter.LEFT)
        self._entry = tkinter.Entry(frame, width=50)
        self._entry.insert(tkinter.END, text)
        self._entry.pack(side=tkinter.LEFT)

    def _reload_cb(self):
        self._hints.delete(0, tkinter.END)
        for hint in usrp2_card_burner.get_raw_device_hints():
            self._hints.insert(tkinter.END, hint)

    def _listbox_cb(self, event):
        try:
            sel = self._hints.get(self._hints.curselection()[0])
            self._entry.delete(0, tkinter.END)
            self._entry.insert(0, sel)
        except Exception as e: print(e)

    def get_devname(self):
        return self._entry.get()

class SectionLabel(tkinter.Label):
    """
    Make a text label with bold font.
    """

    def __init__(self, root, text):
        tkinter.Label.__init__(self, root, text=text)

        #set the font bold
        f = tkinter.font.Font(font=self['font'])
        f['weight'] = 'bold'
        self['font'] = f.name

class USRP2CardBurnerApp(tkinter.Frame):
    """
    The top level gui application for the usrp2 sd card burner.
    Creates entry widgets and button with callback to write images.
    """

    def __init__(self, root, dev, fw, fpga):

        tkinter.Frame.__init__(self, root)

        #pack the file entry widgets
        SectionLabel(self, text="Select Images").pack(pady=5)
        self._fw_img_entry = BinFileEntry(self, "Firmware Image", def_path=fw)
        self._fw_img_entry.pack()
        self._fpga_img_entry = BinFileEntry(self, "FPGA Image", def_path=fpga)
        self._fpga_img_entry.pack()

        #pack the destination entry widget
        SectionLabel(self, text="Select Device").pack(pady=5)
        self._raw_dev_entry = DeviceEntryWidget(self, text=dev)
        self._raw_dev_entry.pack()

        #the do it button
        SectionLabel(self, text="").pack(pady=5)
        tkinter.Label(self, text="Warning! This tool can overwrite your hard drive. Use with caution.").pack()
        tkinter.Button(self, text="Burn SD Card", command=self._burn).pack()

    def _burn(self):
        #grab strings from the gui
        fw = self._fw_img_entry.get_filename()
        fpga = self._fpga_img_entry.get_filename()
        dev = self._raw_dev_entry.get_devname()

        #check input
        if not dev:
            tkinter.messagebox.showerror('Error:', 'No device specified!')
            return
        if not fw and not fpga:
            tkinter.messagebox.showerror('Error:', 'No images specified!')
            return
        if fw and not os.path.exists(fw):
            tkinter.messagebox.showerror('Error:', 'Firmware image not found!')
            return
        if fpga and not os.path.exists(fpga):
            tkinter.messagebox.showerror('Error:', 'FPGA image not found!')
            return

        #burn the sd card
        try:
            verbose = usrp2_card_burner.burn_sd_card(dev=dev, fw=fw, fpga=fpga)
            tkinter.messagebox.showinfo('Verbose:', verbose)
        except Exception as e:
            tkinter.messagebox.showerror('Verbose:', 'Error: %s'%str(e))

########################################################################
# main
########################################################################
if __name__=='__main__':
    options = usrp2_card_burner.get_options()
    root = tkinter.Tk()
    root.title('USRP2 SD Card Burner')
    USRP2CardBurnerApp(root, dev=options.dev, fw=options.fw, fpga=options.fpga).pack()
    root.mainloop()
    exit()


// RUN: %clang_cc1 -triple i386-apple-darwin9 -fsyntax-only -fblocks -Wformat-non-iso -verify %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -fsyntax-only -fblocks -Wformat-non-iso -verify %s

// RUN: %clang_cc1 -triple i386-apple-darwin9 -fdiagnostics-parseable-fixits -fblocks -Wformat-non-iso %s 2>&1 | FileCheck -check-prefix=CHECK -check-prefix=CHECK-32 %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -fdiagnostics-parseable-fixits -fblocks -Wformat-non-iso %s 2>&1 | FileCheck -check-prefix=CHECK -check-prefix=CHECK-64 %s

int printf(const char * restrict, ...);

#if __LP64__
typedef long NSInteger;
typedef unsigned long NSUInteger;
typedef int SInt32;
typedef unsigned int UInt32;

#else

typedef int NSInteger;
typedef unsigned int NSUInteger;
typedef long SInt32;
typedef unsigned long UInt32;
#endif

typedef SInt32 OSStatus;

typedef enum NSIntegerEnum : NSInteger {
  EnumValueA,
  EnumValueB
} NSIntegerEnum;

NSInteger getNSInteger();
NSUInteger getNSUInteger();
SInt32 getSInt32();
UInt32 getUInt32();
NSIntegerEnum getNSIntegerEnum();

void testCorrectionInAllCases() {
  printf("%s", getNSInteger()); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", getNSUInteger()); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%s", getSInt32()); // expected-warning{{values of type 'SInt32' should not be used as format arguments; add an explicit cast to 'int' instead}}
  printf("%s", getUInt32()); // expected-warning{{values of type 'UInt32' should not be used as format arguments; add an explicit cast to 'unsigned int' instead}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-5]]:11-[[@LINE-5]]:13}:"%ld"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:16-[[@LINE-6]]:16}:"(long)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:11-[[@LINE-7]]:13}:"%lu"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:16-[[@LINE-8]]:16}:"(unsigned long)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:11-[[@LINE-9]]:13}:"%d"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-10]]:16-[[@LINE-10]]:16}:"(int)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-11]]:11-[[@LINE-11]]:13}:"%u"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-12]]:16-[[@LINE-12]]:16}:"(unsigned int)"

  printf("%s", getNSIntegerEnum()); // expected-warning{{enum values with underlying type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
}

@interface Foo {
@public
  NSInteger _value;
}
- (NSInteger)getInteger;

@property NSInteger value;
@end

struct Bar {
  NSInteger value;
};

void testParens(Foo *obj, struct Bar *record) {
  NSInteger arr[4] = {0};
  NSInteger i = 0;

  // These cases match the relevant cases in CheckPrintfHandler::checkFormatExpr.
  printf("%s", arr[0]);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", getNSInteger());  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", i);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", obj->_value);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", [obj getInteger]);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", obj.value);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", record->value);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", (i ? i : i));  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", *arr);  // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK-NOT: fix-it:{{.*}}:")"

  printf("%s", i ? i : i); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)("
  // CHECK: fix-it:"{{.*}}":{[[@LINE-4]]:25-[[@LINE-4]]:25}:")"
}

#if __LP64__

void testWarn() {
  printf("%d", getNSInteger()); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%u", getNSUInteger()); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%ld", getSInt32()); // expected-warning{{values of type 'SInt32' should not be used as format arguments; add an explicit cast to 'int' instead}}
  printf("%lu", getUInt32()); // expected-warning{{values of type 'UInt32' should not be used as format arguments; add an explicit cast to 'unsigned int' instead}}

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-5]]:11-[[@LINE-5]]:13}:"%ld"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-6]]:16-[[@LINE-6]]:16}:"(long)"

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-7]]:11-[[@LINE-7]]:13}:"%lu"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-8]]:16-[[@LINE-8]]:16}:"(unsigned long)"

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-9]]:11-[[@LINE-9]]:14}:"%d"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-10]]:17-[[@LINE-10]]:17}:"(int)"

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-11]]:11-[[@LINE-11]]:14}:"%u"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-12]]:17-[[@LINE-12]]:17}:"(unsigned int)"

  printf("%d", getNSIntegerEnum()); // expected-warning{{enum values with underlying type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
}

void testPreserveHex() {
  printf("%x", getNSInteger()); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%x", getNSUInteger()); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-3]]:11-[[@LINE-3]]:13}:"%lx"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-4]]:16-[[@LINE-4]]:16}:"(long)"

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-5]]:11-[[@LINE-5]]:13}:"%lx"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-6]]:16-[[@LINE-6]]:16}:"(unsigned long)"
}

void testSignedness(NSInteger i, NSUInteger u) {
  printf("%d", u); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%i", u); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%u", i); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-4]]:11-[[@LINE-4]]:13}:"%lu"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-4]]:11-[[@LINE-4]]:13}:"%lu"
  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-4]]:11-[[@LINE-4]]:13}:"%ld"
}

void testNoWarn() {
  printf("%ld", getNSInteger()); // no-warning
  printf("%lu", getNSUInteger()); // no-warning
  printf("%d", getSInt32()); // no-warning
  printf("%u", getUInt32()); // no-warning
  printf("%ld", getNSIntegerEnum()); // no-warning
}

#else

void testWarn() {
  printf("%ld", getNSInteger()); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%lu", getNSUInteger()); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%d", getSInt32()); // expected-warning{{values of type 'SInt32' should not be used as format arguments; add an explicit cast to 'int' instead}}
  printf("%u", getUInt32()); // expected-warning{{values of type 'UInt32' should not be used as format arguments; add an explicit cast to 'unsigned int' instead}}

  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-5]]:17-[[@LINE-5]]:17}:"(long)"
  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-5]]:17-[[@LINE-5]]:17}:"(unsigned long)"
  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-5]]:16-[[@LINE-5]]:16}:"(int)"
  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-5]]:16-[[@LINE-5]]:16}:"(unsigned int)"

  printf("%ld", getNSIntegerEnum()); // expected-warning{{enum values with underlying type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-2]]:17-[[@LINE-2]]:17}:"(long)"
}

void testPreserveHex() {
  printf("%lx", getNSInteger()); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%lx", getNSUInteger()); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}

  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-3]]:17-[[@LINE-3]]:17}:"(long)"
  // CHECK-32: fix-it:"{{.*}}":{[[@LINE-3]]:17-[[@LINE-3]]:17}:"(unsigned long)"
}

void testNoWarn() {
  printf("%d", getNSInteger()); // no-warning
  printf("%u", getNSUInteger()); // no-warning
  printf("%ld", getSInt32()); // no-warning
  printf("%lu", getUInt32()); // no-warning
  printf("%d", getNSIntegerEnum()); // no-warning
}

void testSignedness(NSInteger i, NSUInteger u) {
  // It is valid to use a specifier with the opposite signedness as long as
  // the type is correct.
  printf("%d", u); // no-warning
  printf("%i", u); // no-warning
  printf("%u", i); // no-warning
}

#endif

void testCasts() {
  printf("%s", (NSInteger)0); // expected-warning{{values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}
  printf("%s", (NSUInteger)0); // expected-warning{{values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead}}
  printf("%s", (SInt32)0); // expected-warning{{values of type 'SInt32' should not be used as format arguments; add an explicit cast to 'int' instead}}
  printf("%s", (UInt32)0); // expected-warning{{values of type 'UInt32' should not be used as format arguments; add an explicit cast to 'unsigned int' instead}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-5]]:11-[[@LINE-5]]:13}:"%ld"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:16-[[@LINE-6]]:27}:"(long)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:11-[[@LINE-7]]:13}:"%lu"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:16-[[@LINE-8]]:28}:"(unsigned long)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:11-[[@LINE-9]]:13}:"%d"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-10]]:16-[[@LINE-10]]:24}:"(int)"

  // CHECK: fix-it:"{{.*}}":{[[@LINE-11]]:11-[[@LINE-11]]:13}:"%u"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-12]]:16-[[@LINE-12]]:24}:"(unsigned int)"

  printf("%s", (NSIntegerEnum)0); // expected-warning{{enum values with underlying type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:31}:"(long)"
}

void testCapitals() {
  printf("%D", 1); // expected-warning{{conversion specifier is not supported by ISO C}} expected-note {{did you mean to use 'd'?}}
  printf("%U", 1); // expected-warning{{conversion specifier is not supported by ISO C}} expected-note {{did you mean to use 'u'?}}
  printf("%O", 1); // expected-warning{{conversion specifier is not supported by ISO C}} expected-note {{did you mean to use 'o'?}}

  // CHECK: fix-it:"{{.*}}":{[[@LINE-4]]:12-[[@LINE-4]]:13}:"d"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-4]]:12-[[@LINE-4]]:13}:"u"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-4]]:12-[[@LINE-4]]:13}:"o"

  printf("%lD", 1); // expected-warning{{conversion specifier is not supported by ISO C}} expected-note {{did you mean to use 'd'?}} expected-warning{{format specifies type 'long' but the argument has type 'int'}}

  // FIXME: offering two somewhat-conflicting fixits is less than ideal.
  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:13-[[@LINE-3]]:14}:"d"
  // CHECK: fix-it:"{{.*}}":{[[@LINE-4]]:11-[[@LINE-4]]:14}:"%D"
}

void testLayeredTypedefs(OSStatus i) {
  printf("%s", i); // expected-warning {{values of type 'OSStatus' should not be used as format arguments}}
  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
}


""" pretrain a word2vec on the corpus"""
import argparse
import json
import logging
import os
from os.path import join, exists
from time import time
from datetime import timedelta

from cytoolz import concatv
import gensim

from utils import count_data

try:
    DATA_DIR = os.environ['DATA']
except KeyError:
    print('please use environment variable to specify data directories')

class Sentences(object):
    """ needed for gensim word2vec training"""
    def __init__(self):
        self._path = join(DATA_DIR, 'train')
        self._n_data = count_data(self._path)

    def __iter__(self):
        for i in range(self._n_data):
            with open(join(self._path, '{}.json'.format(i))) as f:
                data = json.loads(f.read())
            for s in concatv(data['article'], data['abstract']):
                yield ['<s>'] + s.lower().split() + [r'<\s>']

def main(args):
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',
                        level=logging.INFO)
    start = time()
    save_dir = args.path
    if not exists(save_dir):
        os.makedirs(save_dir)

    sentences = Sentences()
    model = gensim.models.Word2Vec(
        size=args.dim, min_count=5, workers=16, sg=1)
    model.build_vocab(sentences)
    print('vocab built in {}'.format(timedelta(seconds=time()-start)))
    model.train(sentences,
                total_examples=model.corpus_count, epochs=model.iter)

    model.save(join(save_dir, 'word2vec.{}d.{}k.bin'.format(
        args.dim, len(model.wv.vocab)//1000)))
    model.wv.save_word2vec_format(join(
        save_dir,
        'word2vec.{}d.{}k.w2v'.format(args.dim, len(model.wv.vocab)//1000)
    ))

    print('word2vec trained in {}'.format(timedelta(seconds=time()-start)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='train word2vec embedding used for model initialization'
    )
    parser.add_argument('--path', required=True, help='root of the model')
    parser.add_argument('--dim', action='store', type=int, default=128)
    args = parser.parse_args()

    main(args)


; config options
; The island of trust is at example.com
server:
	local-zone: "example.com." transparent
	local-data: "mail.example.com. IN A 10.20.30.40"

stub-zone:
	name: "."
	stub-addr: 193.0.14.129 	# K.ROOT-SERVERS.NET.
CONFIG_END

SCENARIO_BEGIN Test local data with transparent zone queried for types

; K.ROOT-SERVERS.NET.
RANGE_BEGIN 0 100
	ADDRESS 193.0.14.129
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
. IN NS
SECTION ANSWER
. IN NS	K.ROOT-SERVERS.NET.
SECTION ADDITIONAL
K.ROOT-SERVERS.NET.	IN	A	193.0.14.129
ENTRY_END

ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR AA NXDOMAIN
SECTION QUESTION
mail.example.com. IN AAAA
SECTION ANSWER
SECTION AUTHORITY
. IN SOA invalid. invalid. 1 2 3 4 5
ENTRY_END
RANGE_END

STEP 1 QUERY
ENTRY_BEGIN
REPLY RD DO
SECTION QUESTION
mail.example.com. IN A
ENTRY_END
; get straight answer from localdata

STEP 10 CHECK_ANSWER
ENTRY_BEGIN
MATCH all
REPLY QR AA RD RA DO NOERROR
SECTION QUESTION
mail.example.com. IN A
SECTION ANSWER
mail.example.com. IN A 10.20.30.40
SECTION AUTHORITY
ENTRY_END

STEP 20 QUERY
ENTRY_BEGIN
REPLY RD DO
SECTION QUESTION
mail.example.com. IN AAAA
ENTRY_END
; must be NOERROR/NODATA because of A record, not NXDOMAIN from internet.

STEP 30 CHECK_ANSWER
ENTRY_BEGIN
MATCH all
REPLY QR AA RD RA DO NOERROR
SECTION QUESTION
mail.example.com. IN AAAA
SECTION ANSWER
SECTION AUTHORITY
ENTRY_END

SCENARIO_END


/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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.
 */

package com.android.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

/**
 * An implementation of {@link IAbstractFile} extending {@link File}.
 */
public class FileWrapper extends File implements IAbstractFile {
    private static final long serialVersionUID = 1L;

    /**
     * Creates a new File instance matching a given {@link File} object.
     * @param file the file to match
     */
    public FileWrapper(File file) {
        super(file.getAbsolutePath());
    }

    /**
     * Creates a new File instance from a parent abstract pathname and a child pathname string.
     * @param parent the parent pathname
     * @param child the child name
     *
     * @see File#File(File, String)
     */
    public FileWrapper(File parent, String child) {
        super(parent, child);
    }

    /**
     * Creates a new File instance by converting the given pathname string into an abstract
     * pathname.
     * @param osPathname the OS pathname
     *
     * @see File#File(String)
     */
    public FileWrapper(String osPathname) {
        super(osPathname);
    }

    /**
     * Creates a new File instance from a parent abstract pathname and a child pathname string.
     * @param parent the parent pathname
     * @param child the child name
     *
     * @see File#File(String, String)
     */
    public FileWrapper(String parent, String child) {
        super(parent, child);
    }

    /**
     * Creates a new File instance by converting the given file: URI into an
     * abstract pathname.
     * @param uri An absolute, hierarchical URI with a scheme equal to "file", a non-empty path
     * component, and undefined authority, query, and fragment components
     *
     * @see File#File(URI)
     */
    public FileWrapper(URI uri) {
        super(uri);
    }

    @Override
    public InputStream getContents() throws StreamException {
        try {
            return new FileInputStream(this);
        } catch (FileNotFoundException e) {
            throw new StreamException(e, this, StreamException.Error.FILENOTFOUND);
        }
    }

    @Override
    public void setContents(InputStream source) throws StreamException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(this);

            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = source.read(buffer)) != -1) {
                fos.write(buffer, 0, count);
            }
        } catch (IOException e) {
            throw new StreamException(e, this);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new StreamException(e, this);
                }
            }
        }
    }

    @Override
    public OutputStream getOutputStream() throws StreamException {
        try {
            return new FileOutputStream(this);
        } catch (FileNotFoundException e) {
            throw new StreamException(e, this);
        }
    }

    @Override
    public PreferredWriteMode getPreferredWriteMode() {
        return PreferredWriteMode.OUTPUTSTREAM;
    }

    @Override
    public String getOsLocation() {
        return getAbsolutePath();
    }

    @Override
    public boolean exists() {
        return isFile();
    }

    @Override
    public long getModificationStamp() {
        return lastModified();
    }

    @Override
    public IAbstractFolder getParentFolder() {
        String p = this.getParent();
        if (p == null) {
            return null;
        }
        return new FolderWrapper(p);
    }
}


/**
 * Implements hook_update_dependencies().
 */
function {{ machine_name }}_update_dependencies() {
  // Indicate that the mymodule_update_8001() function provided by this module
  // must run after the another_module_update_8003() function provided by the
  // 'another_module' module.
  $dependencies['mymodule'][8001] = [
    'another_module' => 8003,
  ];
  // Indicate that the mymodule_update_8002() function provided by this module
  // must run before the yet_another_module_update_8005() function provided by
  // the 'yet_another_module' module. (Note that declaring dependencies in this
  // direction should be done only in rare situations, since it can lead to the
  // following problem: If a site has already run the yet_another_module
  // module's database updates before it updates its codebase to pick up the
  // newest mymodule code, then the dependency declared here will be ignored.)
  $dependencies['yet_another_module'][8005] = [
    'mymodule' => 8002,
  ];
  return $dependencies;
}


.content p, .content li


import {
  useSharedRef,
  SharedRefMind,
  RefSharedMessage,
  RefSharedMessageType,
  BroadcastMessageEvent,
  refShared
} from "../../src";
import { createVue, nextTick } from "../utils";
import { getCurrentInstance } from "../../src/api";

// import * as compositionApi from '../../src/api';
// import { PASSIVE_EV } from '@vue-composable/core';

describe("sharedRef", () => {
  const _broadcastChannel = window.BroadcastChannel;
  const addEventListenerFn = jest.fn();
  const removeEventListenerFn = jest.fn();
  const postMessageFn = jest.fn();
  const closeFn = jest.fn();
  const constructorFn = jest.fn();
  beforeAll(() => {
    class BroadcastChannel {
      constructor(...args: any[]) {
        constructorFn(...args);
      }
      addEventListener = addEventListenerFn;
      postMessage = postMessageFn;
      close = closeFn;
      removeEventListener = removeEventListenerFn;
    }
    Object.defineProperty(window, "BroadcastChannel", {
      writable: true,
      configurable: true,
      value: BroadcastChannel
    });
    Object.defineProperty(global, "BroadcastChannel", {
      writable: true,
      configurable: true,
      value: BroadcastChannel
    });
  });

  afterAll(() => {
    Object.defineProperty(window, "BroadcastChannel", {
      writable: true,
      configurable: true,
      value: _broadcastChannel
    });
    Object.defineProperty(global, "BroadcastChannel", {
      writable: true,
      configurable: true,
      value: _broadcastChannel
    });
  });

  beforeEach(() => {
    addEventListenerFn.mockReset();
    postMessageFn.mockReset();
    constructorFn.mockReset();
    closeFn.mockReset();
    removeEventListenerFn.mockReset();
  });

  it("should create sharedRef", () => {
    const { mount, destroy } = createVue({
      template: "

",
      setup() {
        const { data, targets } = useSharedRef("test");

        expect(constructorFn).toHaveBeenCalledTimes(1);

        expect(data.value).toBeUndefined();
        expect(targets.value).toHaveLength(0);

        expect(postMessageFn).toBeCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.PING
          } as RefSharedMessage<any>)
        );
        expect(addEventListenerFn).toHaveBeenCalledTimes(3);
        expect(closeFn).not.toHaveBeenCalled();
        return {};
      }
    });
    mount();
    expect(closeFn).not.toHaveBeenCalled();

    destroy();
    expect(closeFn).toHaveBeenCalled();
  });

  it("should create using default value and allow update", () => {
    const { mount } = createVue({
      template: "

",
      setup() {
        const v = {
          data: 1
        };
        const { data, editable } = useSharedRef("test", v);

        expect(data.value).toMatchObject(v);
        expect(editable.value).toBe(true);

        data.value = {
          data: 12
        };
        expect(data.value.data).toBe(12);

        return {};
      }
    });
    mount();
  });

  it("should update to specific mind", () => {
    const { mount, destroy } = createVue({
      template: "

",
      setup() {
        const { mind, setMind, master, editable, targets } = useSharedRef(
          "test"
        );

        expect(mind.value).toBe(SharedRefMind.HIVE);
        expect(master.value).toBe(false);
        expect(editable.value).toBe(true);

        setMind(SharedRefMind.MASTER);

        expect(mind.value).toBe(SharedRefMind.MASTER);
        expect(master.value).toBe(true);
        expect(editable.value).toBe(true);

        expect(postMessageFn).toHaveBeenCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.MASTER
          } as RefSharedMessage<any>)
        );

        setMind(SharedRefMind.HIVE);

        expect(mind.value).toBe(SharedRefMind.HIVE);
        expect(master.value).toBe(false);
        expect(editable.value).toBe(true);

        expect(postMessageFn).toHaveBeenLastCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.HIVE
          } as RefSharedMessage<any>)
        );

        targets.value.push(1, 2, 3, 0);

        return {};
      }
    });
    mount();

    destroy();

    expect(postMessageFn).lastCalledWith(
      expect.objectContaining({
        type: RefSharedMessageType.LEAVE
      } as RefSharedMessage)
    );
  });

  it("should send update events", done => {
    const { mount } = createVue({
      template: "

",
      setup() {
        const { /*mind, setMind, master,*/ data } = useSharedRef("test", {
          v: 1
        });

        const listenerFn =
          addEventListenerFn.mock.calls[
            addEventListenerFn.mock.calls.length - 1
          ][1];

        expect(listenerFn).toBeDefined();
        expect(data.value).toBeDefined();
        expect(postMessageFn).toHaveBeenCalledTimes(2);

        data.value.v++;

        nextTick().then(async x => {
          // expect(postMessageFn).toHaveBeenCalledTimes(2);
          expect(postMessageFn).lastCalledWith(
            expect.objectContaining({
              type: RefSharedMessageType.UPDATE,
              value: data.value
            } as RefSharedMessage)
          );

          const n = {
            x: 1234,
            v: 1234
          };

          data.value = n;

          await nextTick();

          expect(postMessageFn).lastCalledWith(
            expect.objectContaining({
              type: RefSharedMessageType.UPDATE,
              value: n
            } as RefSharedMessage)
          );

          data.value = 1 as any;

          await nextTick();

          expect(postMessageFn).lastCalledWith(
            expect.objectContaining({
              type: RefSharedMessageType.UPDATE,
              value: 1
            } as RefSharedMessage)
          );

          done();
        });
        return {};
      }
    });
    mount();
  });

  it("should reply to events", () => {
    const { mount, destroy } = createVue({
      template: "

",
      setup() {
        const v = { v: 1 };
        const { mind, /* setMind, master,*/ data, targets, id } = useSharedRef(
          "test",
          v
        );

        const listenerFn: (e: BroadcastMessageEvent<RefSharedMessage>) => void =
          addEventListenerFn.mock.calls[
            addEventListenerFn.mock.calls.length - 1
          ][1];

        /* INIT */
        // If init is received it should reply with UPDATE
        listenerFn({
          data: {
            type: RefSharedMessageType.INIT
          } as RefSharedMessage
        } as any);

        expect(postMessageFn).lastCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.UPDATE,
            value: data.value,
            mind: mind.value
          } as RefSharedMessage)
        );
        /* /INIT */

        /* LEAVE */
        // if LEAVE is received we should remove the id from the targets

        targets.value = [1, -1, 111];
        listenerFn({
          data: {
            type: RefSharedMessageType.LEAVE,
            id: 111
          } as RefSharedMessage
        } as any);

        expect(targets.value).toMatchObject([1, -1]);

        // set to master the smallest id and then call the leave again
        listenerFn({
          data: {
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.MASTER,
            id: id
          } as RefSharedMessage
        } as any);

        expect(mind.value).toBe(SharedRefMind.MASTER);

        targets.value = [1, -1];

        listenerFn({
          data: {
            type: RefSharedMessageType.LEAVE,
            id: id
          } as RefSharedMessage
        } as any);

        expect(postMessageFn).lastCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.MASTER,
            id: -1
          } as RefSharedMessage)
        );

        listenerFn({
          data: {
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.HIVE,
            id: id
          } as RefSharedMessage
        } as any);
        expect(mind.value).toBe(SharedRefMind.HIVE);

        targets.value = [];

        /* /LEAVE */

        /* UPDATE */
        // if UPDATE received we should update data and mind

        listenerFn({
          data: {
            type: RefSharedMessageType.UPDATE,
            mind: SharedRefMind.MASTER,
            value: 1
          } as RefSharedMessage
        } as any);

        expect(data.value).toBe(1);
        expect(mind.value).toBe(SharedRefMind.MASTER);

        // restore
        listenerFn({
          data: {
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.HIVE,
            id: id
          } as RefSharedMessage
        } as any);

        /* UPDATE */

        /* PING */
        // if PING received it should send pong event

        targets.value = [1, 2];

        listenerFn({
          data: {
            type: RefSharedMessageType.PING,
            id: id
          } as RefSharedMessage
        } as any);

        // targets are reset and the id is assigned
        expect(targets.value).toStrictEqual([id]);

        expect(postMessageFn).lastCalledWith(
          expect.objectContaining({
            type: RefSharedMessageType.PONG,
            id
          } as RefSharedMessage)
        );

        targets.value = [];
        /* PING */

        /* PONG */
        // if PONG received it should append to targets
        targets.value = [1];

        listenerFn({
          data: {
            type: RefSharedMessageType.PONG,
            id: id
          } as RefSharedMessage
        } as any);

        expect(targets.value).toStrictEqual([1, id]);

        /* PONG */

        // set values for disconnect

        listenerFn({
          data: {
            type: RefSharedMessageType.SET_MIND,
            mind: SharedRefMind.MASTER,
            id: id
          } as RefSharedMessage
        } as any);

        targets.value.push(1, 2, 34, 5, 0);

        return {};
      }
    });
    mount();

    /* ON DISCONNECT */
    destroy();

    expect(postMessageFn).toHaveBeenNthCalledWith(
      postMessageFn.mock.calls.length - 1,
      expect.objectContaining({
        type: RefSharedMessageType.SET_MIND,
        mind: SharedRefMind.MASTER,
        id: 0
      } as RefSharedMessage)
    );

    expect(postMessageFn).lastCalledWith(
      expect.objectContaining({
        type: RefSharedMessageType.LEAVE
      } as RefSharedMessage)
    );

    expect(closeFn).toHaveBeenCalled();
    /* /ON DISCONNECT */
  });

  it("should reply multiple broadcasts", done => {
    const { mount } = createVue({
      template: "

",
      setup() {
        const all = [
          useSharedRef("test"),
          useSharedRef("test"),
          useSharedRef("test")
        ];
        const [b1, b2, b3] = all;

        expect(all.map(x => x.master.value)).toStrictEqual([
          false,
          false,
          false
        ]);

        b1.setMind(SharedRefMind.MASTER);
        b3.mind.value = b2.mind.value = SharedRefMind.MASTER;

        nextTick().then(async () => {
          expect(all.map(x => x.master.value)).toStrictEqual([
            true,
            false,
            false
          ]);

          expect(all.map(x => x.mind.value)).toStrictEqual([
            SharedRefMind.MASTER,
            SharedRefMind.MASTER,
            SharedRefMind.MASTER
          ]);

          expect(all.map(x => x.editable.value)).toStrictEqual([
            true,
            false,
            false
          ]);

          b2.data.value = 12;
          b3.data.value = 22;

          await nextTick();
          expect(b2.data.value).toBe(b1.data.value);
          expect(b3.data.value).toBe(b1.data.value);

          all.forEach(x => x.setMind(SharedRefMind.HIVE));
          await nextTick();

          b2.data.value = 12;
          b3.data.value = 22;

          expect(b2.data.value).not.toBe(b1.data.value);
          expect(b3.data.value).not.toBe(b1.data.value);

          done();
        });

        return {};
      }
    });
    mount();
  });

  describe("helper ref", () => {
    // jest.spyOn(compositionApi, 'getCurrentInstance').mockImplementation(() => 'vue-test-vm');
    it("should create a broadcastChannel", async () => {
      // var el: any = undefined;
      const { mount, destroy } = createVue({
        template: "

",
        setup(props: any, ctx: any) {
          const vm = getCurrentInstance()!;

          // istanbul ignore if
          if (__VUE_2__) {
            (vm as any).$vnode = { tag: "vue-test-vm" };
          } else {
            (vm as any).vnode.scopeId = "vue-test-vm";
          }
          const r = refShared();
          expect(r.value).toBeUndefined();

          expect(constructorFn).toHaveBeenCalled();

          return {};
        }
      });

      mount();
      expect(closeFn).not.toHaveBeenCalled();

      destroy();
      await nextTick();
      expect(closeFn).toHaveBeenCalled();
    });

    it("should set the defaultValue and id ", () => {
      const { mount, destroy } = createVue({
        template: "

",
        setup() {
          const r = refShared(11, "11");
          expect(r.value).toBe(11);

          expect(constructorFn).toHaveBeenCalled();

          return {};
        }
      });
      mount();
      expect(closeFn).not.toHaveBeenCalled();

      destroy();
      expect(closeFn).toHaveBeenCalled();
    });

    it("should warn if used multiple times in the same component", () => {
      const warnSpy = jest.spyOn(console, "warn");

      createVue({
        template: "

",
        setup(_: any, ctx: any) {
          const vm = getCurrentInstance()! as any;
          // istanbul ignore if
          if (__VUE_2__) {
            (vm as any).$vnode = { tag: "vue-test-vm" };
          } else {
            (vm as any).vnode.scopeId = "vue-test-vm";
          }

          const r = refShared();
          const r2 = refShared();

          expect(warnSpy).toHaveBeenCalledWith(
            "[refShared] You can only have one refShared per component, if you need more please assign pass an id refShared(defaultValue, id)"
          );

          return { r, r2 };
        }
      });
    });
  });
});


/*
 * $Id: json_util.c,v 1.4 2006/01/30 23:07:57 mclark Exp $
 *
 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
 * Michael Clark <michael@metaparadigm.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See COPYING for details.
 *
 */

#include "config.h"
#undef realloc

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif /* HAVE_SYS_STAT_H */

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif /* HAVE_FCNTL_H */

#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif /* HAVE_UNISTD_H */

#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <io.h>
#endif /* defined(WIN32) */

#if !defined(HAVE_OPEN) && defined(WIN32)
# define open _open
#endif

#if !defined(HAVE_SNPRINTF) && defined(_MSC_VER)
  /* MSC has the version as _snprintf */
# define snprintf _snprintf
#elif !defined(HAVE_SNPRINTF)
# error You do not have snprintf on your system.
#endif /* HAVE_SNPRINTF */

#include "debug.h"
#include "printbuf.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_tokener.h"
#include "json_util.h"

static int sscanf_is_broken = 0;
static int sscanf_is_broken_testdone = 0;
static void sscanf_is_broken_test(void);
static void _set_last_err(const char *err_fmt, ...);

static char _last_err[256] = "";

const char *json_util_get_last_err()
{
	if (_last_err[0] == '\0')
		return NULL;
	return _last_err;
}

static void _set_last_err(const char *err_fmt, ...)
{
	va_list ap;
	va_start(ap, err_fmt);
	// Ignore (attempted) overruns from snprintf
	(void)vsnprintf(_last_err, sizeof(_last_err), err_fmt, ap);
	va_end(ap);
}

struct json_object* json_object_from_fd(int fd)
{
  struct printbuf *pb;
  struct json_object *obj;
  char buf[JSON_FILE_BUF_SIZE];
  int ret;

  if(!(pb = printbuf_new())) {
    _set_last_err("json_object_from_file: printbuf_new failed\n");
    return NULL;
  }
  while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
    printbuf_memappend(pb, buf, ret);
  }
  if(ret < 0) {
    _set_last_err("json_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno));
    printbuf_free(pb);
    return NULL;
  }
  obj = json_tokener_parse(pb->buf);
  printbuf_free(pb);
  return obj;
}

struct json_object* json_object_from_file(const char *filename)
{
  struct json_object *obj;
  int fd;

  if((fd = open(filename, O_RDONLY)) < 0) {
    _set_last_err("json_object_from_file: error opening file %s: %s\n",
	     filename, strerror(errno));
    return NULL;
  }
  obj = json_object_from_fd(fd);
  close(fd);
  return obj;
}

/* extended "format and write to file" function */

int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags)
{
  const char *json_str;
  int fd, ret;
  unsigned int wpos, wsize;

  if(!obj) {
    _set_last_err("json_object_to_file: object is null\n");
    return -1;
  }

  if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
    _set_last_err("json_object_to_file: error opening file %s: %s\n",
	     filename, strerror(errno));
    return -1;
  }

  if(!(json_str = json_object_to_json_string_ext(obj,flags))) {
    close(fd);
    return -1;
  }

  wsize = (unsigned int)(strlen(json_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */
  wpos = 0;
  while(wpos < wsize) {
    if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
      close(fd);
      _set_last_err("json_object_to_file: error writing file %s: %s\n",
	     filename, strerror(errno));
      return -1;
    }

	/* because of the above check for ret < 0, we can safely cast and add */
    wpos += (unsigned int)ret;
  }

  close(fd);
  return 0;
}

// backwards compatible "format and write to file" function

int json_object_to_file(const char *filename, struct json_object *obj)
{
  return json_object_to_file_ext(filename, obj, JSON_C_TO_STRING_PLAIN);
}

int json_parse_double(const char *buf, double *retval)
{
  return (sscanf(buf, "%lf", retval)==1 ? 0 : 1);
}

/*
 * Not all implementations of sscanf actually work properly.
 * Check whether the one we're currently using does, and if
 * it's broken, enable the workaround code.
 */
static void sscanf_is_broken_test()
{
	int64_t num64;
	int ret_errno, is_int64_min, ret_errno2, is_int64_max;

	(void)sscanf(" -01234567890123456789012345", "%" SCNd64, &num64);
	ret_errno = errno;
	is_int64_min = (num64 == INT64_MIN);

	(void)sscanf(" 01234567890123456789012345", "%" SCNd64, &num64);
	ret_errno2 = errno;
	is_int64_max = (num64 == INT64_MAX);

	if (ret_errno != ERANGE || !is_int64_min ||
	    ret_errno2 != ERANGE || !is_int64_max)
	{
		MC_DEBUG("sscanf_is_broken_test failed, enabling workaround code\n");
		sscanf_is_broken = 1;
	}
}

int json_parse_int64(const char *buf, int64_t *retval)
{
	int64_t num64;
	const char *buf_sig_digits;
	int orig_has_neg;
	int saved_errno;

	if (!sscanf_is_broken_testdone)
	{
		sscanf_is_broken_test();
		sscanf_is_broken_testdone = 1;
	}

	// Skip leading spaces
	while (isspace((int)*buf) && *buf)
		buf++;

	errno = 0; // sscanf won't always set errno, so initialize
	if (sscanf(buf, "%" SCNd64, &num64) != 1)
	{
		MC_DEBUG("Failed to parse, sscanf != 1\n");
		return 1;
	}

	saved_errno = errno;
	buf_sig_digits = buf;
	orig_has_neg = 0;
	if (*buf_sig_digits == '-')
	{
		buf_sig_digits++;
		orig_has_neg = 1;
	}

	// Not all sscanf implementations actually work
	if (sscanf_is_broken && saved_errno != ERANGE)
	{
		char buf_cmp[100];
		char *buf_cmp_start = buf_cmp;
		int recheck_has_neg = 0;
		int buf_cmp_len;

		// Skip leading zeros, but keep at least one digit
		while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
			buf_sig_digits++;
		if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
			orig_has_neg = 0; // "-0" is the same as just plain "0"

		snprintf(buf_cmp_start, sizeof(buf_cmp), "%" PRId64, num64);
		if (*buf_cmp_start == '-')
		{
			recheck_has_neg = 1;
			buf_cmp_start++;
		}
		// No need to skip leading spaces or zeros here.

		buf_cmp_len = strlen(buf_cmp_start);
		/**
		 * If the sign is different, or
		 * some of the digits are different, or
		 * there is another digit present in the original string
		 * then we have NOT successfully parsed the value.
		 */
		if (orig_has_neg != recheck_has_neg ||
		    strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
			((int)strlen(buf_sig_digits) != buf_cmp_len &&
			 isdigit((int)buf_sig_digits[buf_cmp_len])
		    )
		   )
		{
			saved_errno = ERANGE;
		}
	}

	// Not all sscanf impl's set the value properly when out of range.
	// Always do this, even for properly functioning implementations,
	// since it shouldn't slow things down much.
	if (saved_errno == ERANGE)
	{
		if (orig_has_neg)
			num64 = INT64_MIN;
		else
			num64 = INT64_MAX;
	}
	*retval = num64;
	return 0;
}

#ifndef HAVE_REALLOC
void* rpl_realloc(void* p, size_t n)
{
	if (n == 0)
		n = 1;
	if (p == 0)
		return malloc(n);
	return realloc(p, n);
}
#endif

#define NELEM(a)        (sizeof(a) / sizeof(a[0]))
static const char* json_type_name[] = {
  /* If you change this, be sure to update the enum json_type definition too */
  "null",
  "boolean",
  "double",
  "int",
  "object",
  "array",
  "string",
};

const char *json_type_to_name(enum json_type o_type)
{
	int o_type_int = (int)o_type;
	if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name))
	{
		_set_last_err("json_type_to_name: type %d is out of range [0,%d]\n", o_type, NELEM(json_type_name));
		return NULL;
	}
	return json_type_name[o_type];
}


#version 450

layout(binding = 0, std140) uniform Foo
{
    layout(row_major) mat4 lightVP[64];
    uint shadowCascadesNum;
    int test;
} _11;

layout(location = 0) in vec3 fragWorld;
layout(location = 0) out int _entryPointOutput;

int _240;

void main()
{
    uint _227;
    int _236;
    for (;;)
    {
        _227 = 0u;
        bool _231;
        int _237;
        for (;;)
        {
            if (_227 < _11.shadowCascadesNum)
            {
                mat4 _228;
                for (;;)
                {
                    if (_11.test == 0)
                    {
                        _228 = mat4(vec4(0.5, 0.0, 0.0, 0.0), vec4(0.0, 0.5, 0.0, 0.0), vec4(0.0, 0.0, 0.5, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
                        break;
                    }
                    _228 = mat4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
                    break;
                }
                vec4 _177 = (_228 * _11.lightVP[_227]) * vec4(fragWorld, 1.0);
                float _179 = _177.z;
                float _186 = _177.x;
                float _188 = _177.y;
                if ((((_179 >= 0.0) && (_179 <= 1.0)) && (max(_186, _188) <= 1.0)) && (min(_186, _188) >= 0.0))
                {
                    _237 = int(_227);
                    _231 = true;
                    break;
                }
                else
                {
                    _227++;
                    continue;
                }
                _227++;
                continue;
            }
            else
            {
                _237 = _240;
                _231 = false;
                break;
            }
        }
        if (_231)
        {
            _236 = _237;
            break;
        }
        _236 = -1;
        break;
    }
    _entryPointOutput = _236;
}


This operation cancels a cluster job. You can only cancel a cluster job while it's in the AwaitingQuorum status.

To cancel a cluster job

This operation cancels a job. You can only cancel a job before its JobState value changes to PreparingAppliance.

To cancel a job for a Snowball device

This operation creates an address for a job. Addresses are validated at the time of creation. The address you provide must be located within the serviceable area of your region. If the address is invalid or unsupported, then an exception is thrown.

To create an address for a job

MyCluster

Creates an empty cluster. Each cluster supports five nodes. You use the CreateJob action separately to create the jobs for each of these nodes. The cluster does not ship until these five node jobs have been created.

To create a cluster

My Job

Creates a job to import or export data between Amazon S3 and your on-premises data center. Your AWS account must have the right trust policies and permissions in place to create a job for Snowball. If you're creating a job for a node in a cluster, you only need to provide the clusterId value; the other job attributes are inherited from the cluster.

To create a job

This operation describes an address for a job.

To describe an address for a job

This operation describes all the addresses that you've created for AWS Snowball. Calling this API in one of the US regions will return addresses from the list of all addresses associated with this account in all US regions.

To describe all the addresses you've created for AWS Snowball

MyCluster

Returns information about a specific cluster including shipping information, cluster status, and other important metadata.

To describe a cluster

My Job

This operation describes a job you've created for AWS Snowball.

To describe a job you've created for AWS Snowball

Returns a link to an Amazon S3 presigned URL for the manifest file associated with the specified JobId value. You can access the manifest file for up to 60 minutes after this request has been made. To access the manifest file after 60 minutes have passed, you'll have to make another call to the GetJobManifest action.

The manifest is an encrypted file that you can download after your job enters the WithCustomer status. The manifest is decrypted by using the UnlockCode code value, when you pass both values to the Snowball through the Snowball client when the client is started for the first time.

As a best practice, we recommend that you don't save a copy of an UnlockCode value in the same location as the manifest file for that job. Saving these separately helps prevent unauthorized parties from gaining access to the Snowball associated with that job.

The credentials of a given job, including its manifest file and unlock code, expire 90 days after the job is created.

To get the manifest for a job you've created for AWS Snowball

Returns the UnlockCode code value for the specified job. A particular UnlockCode value can be accessed for up to 90 days after the associated job has been created.

The UnlockCode value is a 29-character code with 25 alphanumeric characters and 4 hyphens. This code is used to decrypt the manifest file when it is passed along with the manifest to the Snowball through the Snowball client when the client is started for the first time.

As a best practice, we recommend that you don't save a copy of the UnlockCode in the same location as the manifest file for that job. Saving these separately helps prevent unauthorized parties from gaining access to the Snowball associated with that job.

To get the unlock code for a job you've created for AWS Snowball

Returns information about the Snowball service limit for your account, and also the number of Snowballs your account has in use.

The default service limit for the number of Snowballs that you can have at one time is 1. If you want to increase your service limit, contact AWS Support.

To see your Snowball service limit and the number of Snowballs you have in use

Returns an array of JobListEntry objects of the specified length. Each JobListEntry object is for a job in the specified cluster and contains a job's state, a job's ID, and other information.

To get a list of jobs in a cluster that you've created for AWS Snowball

MyCluster

Returns an array of ClusterListEntry objects of the specified length. Each ClusterListEntry object contains a cluster's state, a cluster's ID, and other important status information.

To get a list of clusters that you've created for AWS Snowball

MyJob

Returns an array of JobListEntry objects of the specified length. Each JobListEntry object contains a job's state, a job's ID, and a value that indicates whether the job is a job part, in the case of export jobs. Calling this API action in one of the US regions will return jobs from the list of all jobs associated with this account in all US regions.

To get a list of jobs that you've created for AWS Snowball

Updated the address to send this to image processing - RJ

This action allows you to update certain parameters for a cluster. Once the cluster changes to a different state, usually within 60 minutes of it being created, this action is no longer available.

To update a cluster

Upgraded to Edge, shipped to Finance Dept, and requested faster shipping speed - TS.

This action allows you to update certain parameters for a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available.

To update a job


     Program PWSCF v.6.0 (svn rev. 13286) starts on  7Feb2017 at 15: 8:46

     This program is part of the open-source Quantum ESPRESSO suite
     for quantum simulation of materials; please cite
         "P. Giannozzi et al., J. Phys.:Condens. Matter 21 395502 (2009);
          URL http://www.quantum-espresso.org",
     in publications or presentations arising from this work. More details at
     http://www.quantum-espresso.org/quote

     Parallel version (MPI), running on     2 processors
     R & G space division:  proc/nbgrp/npool/nimage =       2
     Waiting for input...
     Reading input from standard input
     Message from routine read_cards :
     DEPRECATED: no units specified in ATOMIC_POSITIONS card
     Message from routine read_cards :
     ATOMIC_POSITIONS: units set to alat

     Current dimensions of program PWSCF are:
     Max number of different atomic species (ntypx) = 10
     Max number of k-points (npk) =  40000
     Max angular momentum in pseudopotentials (lmaxx) =  3

     Subspace diagonalization in iterative solution of the eigenvalue problem:
     a serial algorithm will be used

     Parallelization info
     --------------------
     sticks:   dense  smooth     PW     G-vecs:    dense   smooth      PW
     Min         126     126     42                 1365     1365     264
     Max         127     127     43                 1368     1368     267
     Sum         253     253     85                 2733     2733     531

     bravais-lattice index     =            2
     lattice parameter (alat)  =      10.2000  a.u.
     unit-cell volume          =     265.3020 (a.u.)^3
     number of atoms/cell      =            2
     number of atomic types    =            1
     number of electrons       =         8.00
     number of Kohn-Sham states=            4
     kinetic-energy cutoff     =      18.0000  Ry
     charge density cutoff     =      72.0000  Ry
     convergence threshold     =      1.0E-08
     mixing beta               =       0.7000
     number of iterations used =            8  plain     mixing
     Exchange-correlation      =  SLA  PZ   NOGX NOGC ( 1  1  0  0 0 0)

     celldm(1)=  10.200000  celldm(2)=   0.000000  celldm(3)=   0.000000
     celldm(4)=   0.000000  celldm(5)=   0.000000  celldm(6)=   0.000000

     crystal axes: (cart. coord. in units of alat)
               a(1) = (  -0.500000   0.000000   0.500000 )
               a(2) = (   0.000000   0.500000   0.500000 )
               a(3) = (  -0.500000   0.500000   0.000000 )

     reciprocal axes: (cart. coord. in units 2 pi/alat)
               b(1) = ( -1.000000 -1.000000  1.000000 )
               b(2) = (  1.000000  1.000000  1.000000 )
               b(3) = ( -1.000000  1.000000 -1.000000 )

     PseudoPot. # 1 for Si read from file:
     /home/pietro/espresso-svn/pseudo/Si.pz-vbc.UPF
     MD5 check sum: 6dfa03ddd5817404712e03e4d12deb78
     Pseudo is Norm-conserving, Zval =  4.0
     Generated by new atomic code, or converted to UPF format
     Using radial grid of  431 points,  2 beta functions with:
                l(1) =   0
                l(2) =   1

     atomic species   valence    mass     pseudopotential
        Si             4.00    28.08600     Si( 1.00)

     48 Sym. Ops., with inversion, found (24 have fractional translation)

   Cartesian axes

     site n.     atom                  positions (alat units)
         1           Si  tau(   1) = (   0.0000000   0.0000000   0.0000000  )
         2           Si  tau(   2) = (   0.2500000   0.2500000   0.2500000  )

     number of k points=    10
                       cart. coord. in units 2pi/alat
        k(    1) = (   0.1250000   0.1250000   0.1250000), wk =   0.0625000
        k(    2) = (   0.1250000   0.1250000   0.3750000), wk =   0.1875000
        k(    3) = (   0.1250000   0.1250000   0.6250000), wk =   0.1875000
        k(    4) = (   0.1250000   0.1250000   0.8750000), wk =   0.1875000
        k(    5) = (   0.1250000   0.3750000   0.3750000), wk =   0.1875000
        k(    6) = (   0.1250000   0.3750000   0.6250000), wk =   0.3750000
        k(    7) = (   0.1250000   0.3750000   0.8750000), wk =   0.3750000
        k(    8) = (   0.1250000   0.6250000   0.6250000), wk =   0.1875000
        k(    9) = (   0.3750000   0.3750000   0.3750000), wk =   0.0625000
        k(   10) = (   0.3750000   0.3750000   0.6250000), wk =   0.1875000

     Dense  grid:     2733 G-vectors     FFT dimensions: (  20,  20,  20)

     Estimated max dynamical RAM per process >       1.01MB

     Estimated total allocated dynamical RAM >       2.01MB

     Initial potential from superposition of free atoms

     starting charge    7.99901, renormalised to    8.00000
     Starting wfc are    8 randomized atomic wfcs

     total cpu time spent up to now is        0.0 secs

     per-process dynamical memory:     4.2 Mb

     Self-consistent Calculation

     iteration #  1     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  1.00E-02,  avg # of iterations =  2.0

     Threshold (ethr) on eigenvalues was too large:
     Diagonalizing with lowered threshold

     Davidson diagonalization with overlap
     ethr =  7.76E-04,  avg # of iterations =  1.0

     total cpu time spent up to now is        0.1 secs

     total energy              =     -15.84097902 Ry
     Harris-Foulkes estimate   =     -15.86196351 Ry
     estimated scf accuracy    <       0.06138430 Ry

     iteration #  2     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  7.67E-04,  avg # of iterations =  1.0

     total cpu time spent up to now is        0.1 secs

     total energy              =     -15.84406671 Ry
     Harris-Foulkes estimate   =     -15.84437190 Ry
     estimated scf accuracy    <       0.00214543 Ry

     iteration #  3     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  2.68E-05,  avg # of iterations =  2.5

     total cpu time spent up to now is        0.1 secs

     total energy              =     -15.84451033 Ry
     Harris-Foulkes estimate   =     -15.84454240 Ry
     estimated scf accuracy    <       0.00007065 Ry

     iteration #  4     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  8.83E-07,  avg # of iterations =  2.2

     total cpu time spent up to now is        0.1 secs

     total energy              =     -15.84452622 Ry
     Harris-Foulkes estimate   =     -15.84452930 Ry
     estimated scf accuracy    <       0.00000678 Ry

     iteration #  5     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  8.48E-08,  avg # of iterations =  2.0

     total cpu time spent up to now is        0.1 secs

     total energy              =     -15.84452724 Ry
     Harris-Foulkes estimate   =     -15.84452726 Ry
     estimated scf accuracy    <       0.00000006 Ry

     iteration #  6     ecut=    18.00 Ry     beta=0.70
     Davidson diagonalization with overlap
     ethr =  7.23E-10,  avg # of iterations =  2.6

     total cpu time spent up to now is        0.1 secs

     End of self-consistent calculation

          k = 0.1250 0.1250 0.1250 (   335 PWs)   bands (ev):

    -5.6039   4.6467   5.9568   5.9568

          k = 0.1250 0.1250 0.3750 (   338 PWs)   bands (ev):

    -5.0584   3.0175   4.9012   4.9909

          k = 0.1250 0.1250 0.6250 (   337 PWs)   bands (ev):

    -3.9883   1.3106   3.5165   3.9919

          k = 0.1250 0.1250 0.8750 (   343 PWs)   bands (ev):

    -2.4615  -0.5936   2.7226   3.5069

          k = 0.1250 0.3750 0.3750 (   341 PWs)   bands (ev):

    -4.5395   1.5909   3.8905   5.4637

          k = 0.1250 0.3750 0.6250 (   340 PWs)   bands (ev):

    -3.5491   0.3750   2.8565   4.2745

          k = 0.1250 0.3750 0.8750 (   347 PWs)   bands (ev):

    -2.2719  -0.7033   2.0783   3.2106

          k = 0.1250 0.6250 0.6250 (   344 PWs)   bands (ev):

    -2.8220  -0.4390   2.1614   4.3230

          k = 0.3750 0.3750 0.3750 (   350 PWs)   bands (ev):

    -4.0849   0.2304   5.1432   5.1432

          k = 0.3750 0.3750 0.6250 (   343 PWs)   bands (ev):

    -3.3347  -0.5842   3.9340   4.6556

     highest occupied level (ev):     5.9568

!    total energy              =     -15.84452726 Ry
     Harris-Foulkes estimate   =     -15.84452726 Ry
     estimated scf accuracy    <          8.6E-10 Ry

     The total energy is the sum of the following terms:

     one-electron contribution =       4.79352707 Ry
     hartree contribution      =       1.07664111 Ry
     xc contribution           =      -4.81493678 Ry
     ewald contribution        =     -16.89975867 Ry

     convergence has been achieved in   6 iterations

     Writing output data file si.save

     init_run     :      0.02s CPU      0.03s WALL (       1 calls)
     electrons    :      0.08s CPU      0.08s WALL (       1 calls)

     Called by init_run:
     wfcinit      :      0.01s CPU      0.01s WALL (       1 calls)
     potinit      :      0.00s CPU      0.00s WALL (       1 calls)

     Called by electrons:
     c_bands      :      0.06s CPU      0.06s WALL (       7 calls)
     sum_band     :      0.02s CPU      0.02s WALL (       7 calls)
     v_of_rho     :      0.00s CPU      0.00s WALL (       7 calls)
     mix_rho      :      0.00s CPU      0.00s WALL (       7 calls)

     Called by c_bands:
     init_us_2    :      0.01s CPU      0.00s WALL (     150 calls)
     cegterg      :      0.05s CPU      0.06s WALL (      70 calls)

     Called by sum_band:

     Called by *egterg:
     h_psi        :      0.04s CPU      0.05s WALL (     213 calls)
     g_psi        :      0.00s CPU      0.00s WALL (     133 calls)
     cdiaghg      :      0.00s CPU      0.01s WALL (     193 calls)

     Called by h_psi:
     h_psi:pot    :      0.04s CPU      0.04s WALL (     213 calls)
     h_psi:calbec :      0.00s CPU      0.00s WALL (     213 calls)
     vloc_psi     :      0.04s CPU      0.04s WALL (     213 calls)
     add_vuspsi   :      0.00s CPU      0.00s WALL (     213 calls)

     General routines
     calbec       :      0.00s CPU      0.00s WALL (     213 calls)
     fft          :      0.00s CPU      0.00s WALL (      29 calls)
     fftw         :      0.04s CPU      0.04s WALL (    1954 calls)
     davcio       :      0.00s CPU      0.00s WALL (      10 calls)

     Parallel routines
     fft_scatter  :      0.01s CPU      0.01s WALL (    1983 calls)

     PWSCF        :     0.16s CPU         0.16s WALL

   This run was terminated on:  15: 8:46   7Feb2017

=------------------------------------------------------------------------------=
   JOB DONE.
=------------------------------------------------------------------------------=


import java.util.Arrays;

/**
 * Author: 王俊超
 * Date: 2016-01-08 15:13
 * CSDN: http://blog.csdn.net/derrantcm
 * Github: https://github.com/Wang-Jun-Chao
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        NextElement ne = new NextElement();
        int[] ints = {11, 13, 10, 5, 12, 21, 3};
        System.out.println(Arrays.toString(ne.findNext(ints, ints.length)));
    }
}


<?xml version="1.0" encoding="UTF-8" ?>
<Page loaded="pageLoaded">
    <ScrollView orientation="vertical" row="1">
        <WrapLayout id="wrapLayoutWithExamples"/>
    </ScrollView>
</Page>


"use strict";

var _ = require('underscore');
var path = require('path');
var config = new(require('./config'))();
var MetadataComponent = require('./metadata-component');

var folderBasedMetadataMap = config.get('folderBasedMetadataMap');
var standardPicklistMapping = config.get('standardPicklistMapping');
var nonEditableManagedMetadataTypes = config.get('nonEditableManagedMetadataTypes');

var getFolderTypes = function() {
	var folderTypes = [];
	Object.keys(folderBasedMetadataMap).forEach(function(key) {
		folderTypes.push(key);
		folderTypes.push(folderBasedMetadataMap[key]);
	});
	return folderTypes;
}

var FetchResultParser = module.exports = function(resultJSON) {
	var self = this;
	self.resultJSON = JSON.parse(JSON.stringify(resultJSON));
	self.apiVersions = self.resultJSON.apiVersions || [];
	self.describeMetadataResult = self.resultJSON.describeMetadataResult || {};
	self.fileProperties = self.resultJSON.fileProperties || [];
	self.personAccountRecordTypes = self.resultJSON.personAccountRecordTypes || [];
	self.flowDefinitions = self.resultJSON.flowDefinitions || [];
	self.warnings = self.resultJSON.warnings || [];
};

FetchResultParser.prototype.getApiVersion = function() {
	var self = this;
	var versions = self.apiVersions;
	if (Array.isArray(versions) && versions.length) {
		return versions[versions.length - 1].version;
	}
	return null;
};

FetchResultParser.prototype.getComponents = function(opts) {
	var self = this;
	opts = opts ? opts : {};
	opts.recursive = opts.recursive !== undefined ? opts.recursive : true;
	opts.filterInstalledPackages = opts.filterInstalledPackages !== undefined ? opts.filterInstalledPackages : true;
	opts.filterManaged = opts.filterManaged !== undefined ? opts.filterManaged : true;
	var components = [];
	if (opts.filterInstalledPackages) {
		self.filterInstalledPackages();
	}
	if (opts.filterManaged) {
		self.filterManaged();
	} else {
		self.filterNonWritableManaged();
	}
	self.transform();
	self.addStandardPicklists();
	self.filterInvalid();
	if (opts.recursive) {
		self.filterSuperfluousParents();
	} else {
		self.filterChildren();
	}
	self.fileProperties.forEach(function(fileProperty) {
		components.push(
			new MetadataComponent({
				type: fileProperty.type,
				fullName: fileProperty.fullName,
				fileName: fileProperty.fileName ? path.join.apply(null, fileProperty.fileName.split('/')) : fileProperty.fileName
			})
		);
	});
	return components;
};

FetchResultParser.prototype.getWarnings = function() {
	return this.warnings;
}

FetchResultParser.prototype.filterInstalledPackages = function() {
	var self = this;
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		return fileProperty.type !== 'InstalledPackage';
	});
	return self;
}

FetchResultParser.prototype.filterManaged = function() {
	var self = this;
	// filter installed metadata components
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		return fileProperty.manageableState !== 'installed';
	});
	return self;
}

FetchResultParser.prototype.filterNonWritableManaged = function() {
	var self = this;
	// filter installed metadata components
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		return !(fileProperty.manageableState === 'installed' && nonEditableManagedMetadataTypes.indexOf(fileProperty.type) >= 0);
	});
	return self;
}

FetchResultParser.prototype.addStandardPicklists = function() {
	var self = this;
	var availableCustomObjectNames = _.pluck(_.where(self.fileProperties, {
		type: 'CustomObject'
	}), 'fullName');

	// Workaround for https://success.salesforce.com/ideaView?id=0873A000000cMdrQAE
	var standardValueSetAvailable = _.findWhere(self.describeMetadataResult.metadataObjects, {
		xmlName: 'StandardValueSet'
	});

	Object.keys(standardPicklistMapping).forEach(function(standardField) {
		var customObjectName = standardField.split('.')[0];
		if (availableCustomObjectNames.indexOf(customObjectName) >= 0) {
			if (standardValueSetAvailable) {
				// Picklists represented as StandardValueSet (>= 38.0)
				var standardValueSetName = standardPicklistMapping[standardField];
				self.fileProperties.push({
					type: 'StandardValueSet',
					fullName: standardValueSetName,
					fileName: standardValueSetName + '.standardValueSet'
				});
			} else {
				// Picklists represented as CustomField (< 38.0)
				self.fileProperties.push({
					type: 'CustomField',
					fullName: standardField,
					fileName: customObjectName + '.object'
				});
			}
		}
	});
}

FetchResultParser.prototype.transform = function() {
	var self = this;
	var majorApiVersion = parseInt(config.get('defaultApiVersion'));
	var describeMetadataService = new(require('./describe-metadata-service'))(self.describeMetadataResult);
	var metadataObjectsExtended = describeMetadataService.getTypes();
	self.fileProperties = self.fileProperties.map(function(fileProperty) {
		if (typeof fileProperty.fileName === 'string' && (!fileProperty.type || typeof fileProperty.type !== 'string')) {
			// Problem: listMetadata returns some entries with `"type": { "$": { "xsi:nil": "true" } }`.
			// Currently this is known for entries of `StandardValueSetTranslation` and `GlobalValueSetTranslation`.
			// Workaround: try to determine type based on fileName
			var metadataType = _.findWhere(metadataObjectsExtended, {
				directoryName: fileProperty.fileName.split('/')[0]
			});
			if (metadataType) {
				fileProperty.type = metadataType.xmlName;
			}
		}
		if (Object.keys(folderBasedMetadataMap).indexOf(fileProperty.type) > -1) {
			// DocumentFolder has to be listed as Document
			fileProperty.type = folderBasedMetadataMap[fileProperty.type];
		} else if (majorApiVersion < 44 && fileProperty.type === 'Flow' && !new RegExp('^.*-[0-9]+$').test(fileProperty.fullName) && self.flowDefinitions) {
			// determine the active version number using the FlowDefinition Metadata
			var flowDefinitionMatch = _.findWhere(self.flowDefinitions, {
				DeveloperName: fileProperty.fullName
			});
			if (flowDefinitionMatch && flowDefinitionMatch.ActiveVersion && flowDefinitionMatch.ActiveVersion.VersionNumber) {
				fileProperty.fullName = fileProperty.fullName + '-' + flowDefinitionMatch.ActiveVersion.VersionNumber;
			}
		} else if (['CustomMetadata', 'Layout', 'QuickAction'].indexOf(fileProperty.type) >= 0 && fileProperty.manageableState === 'installed' && fileProperty.namespacePrefix) {
			// https://gearset.com/blog/retrieving-and-deploying-namespaced-layouts-in-salesforce
			// The namespace prefix seems to be missing for the component names (not for CustomObject names) -> last part
			var separator = fileProperty.type === 'Layout' ? '-' : '.';
			// split only once
			var tmpCmdFullNameParts = fileProperty.fullName.split(separator);
			var cmpFullNameParts = tmpCmdFullNameParts.slice(0, 1);
			if (tmpCmdFullNameParts.length > 1) {
				cmpFullNameParts.push(tmpCmdFullNameParts.slice(1, tmpCmdFullNameParts.length).join(separator));
			}
			var fixedCmpFullName = cmpFullNameParts.map(function(part, index, array) {
				if (index === array.length - 1 && part.indexOf(fileProperty.namespacePrefix + '__') !== 0) {
					return fileProperty.namespacePrefix + '__' + part;
				}
				return part;
			}).join(separator);
			if (fixedCmpFullName !== fileProperty.fullName) {
				var directory = fileProperty.fileName.split("/")[0];
				var fileNameDotParts = fileProperty.fileName.split(".");
				var extension = fileNameDotParts[fileNameDotParts.length - 1];
				fileProperty.fileName = path.join(directory, fixedCmpFullName) + "." + extension;
				fileProperty.fullName = fixedCmpFullName;
			}
		} else if (fileProperty.type === 'RecordType' && self.personAccountRecordTypes) {
			// PersonAccount RecordTypes are being listed incorrectly as Account RecordTypes
			var fullNameParts = fileProperty.fullName.split('.');
			var itemType = fullNameParts[0];
			var itemName = fullNameParts[1];
			var personAccountRecordTypeMatch = _.findWhere(self.personAccountRecordTypes, {
				DeveloperName: itemName,
				SobjectType: itemType,
				IsPersonType: true
			});
			if (personAccountRecordTypeMatch) {
				fileProperty.fullName = 'PersonAccount.' + itemName;
			}
		} else if (fileProperty.type === 'CustomFeedFilter') {
			// Apparently the fullName returned in the FileProperty does not include the necessary Case prefix:
			// http://salesforce.stackexchange.com/questions/156714/listmetadata-query-of-type-customfeedfilter-returns-fullname-without-sobject
			if (fileProperty.fullName.indexOf('.') < 0) {
				fileProperty.fullName = 'Case.' + fileProperty.fullName;
			}
		}
		return fileProperty;
	});
	return self;
};

FetchResultParser.prototype.filterChildren = function() {
	var self = this;
	// https://developer.salesforce.com/docs/atlas.en-us.dev_lifecycle.meta/dev_lifecycle/lifecycle_adv_ant_tool_configuration.htm
	// > You only need to include the parent objects (XMLName fields), because child objects are included with their parents when retrieving or deploying metadata with the Force.com Migration Tool.
	var allChildXmlNames = [];
	self.describeMetadataResult.metadataObjects.forEach(function(metadataType) {
		if (metadataType.childXmlNames) {
			allChildXmlNames = allChildXmlNames.concat(metadataType.childXmlNames);
		}
	});
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		if (allChildXmlNames.indexOf(fileProperty.type) >= 0) {
			return false;
		}
		return true;
	});
	return self;
}

FetchResultParser.prototype.filterSuperfluousParents = function() {
	var self = this;
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		var metadataType = _.findWhere(self.describeMetadataResult.metadataObjects, {
			xmlName: fileProperty.type
		});
		// don't list types which have named children only
		return !(metadataType && metadataType.childXmlNames && ['CustomObject', 'Profile', 'PermissionSet'].indexOf(fileProperty.type) < 0);
	});
	return self;
}

FetchResultParser.prototype.filterInvalid = function() {
	var self = this;
	var majorApiVersion = parseInt(config.get('defaultApiVersion'));
	var folderTypes = getFolderTypes();
	self.fileProperties = _.filter(self.fileProperties, function(fileProperty) {
		if (!fileProperty.type || typeof fileProperty.type !== 'string') {
			self.warnings.push('Warning: Skipped file property missing type: ' + JSON.stringify(fileProperty));
			return false;
		}
		if (folderTypes.indexOf(fileProperty.type) > -1 && fileProperty.fullName === 'unfiled$public') {
			// we don't consider this as a warning
			// self.warnings.push('Warning: Skipped standard ' + fileProperty.type + ': ' + fileProperty.fullName);
			return false;
		} else if (fileProperty.type === 'QuickAction' && new RegExp('^09D26.*').test(fileProperty.id)) {
			self.warnings.push('Warning: Skipped non-global QuickAction: ' + fileProperty.fullName);
			return false;
		} else if (majorApiVersion < 44 && fileProperty.type === 'Flow' && !new RegExp('^.*-[0-9]+$').test(fileProperty.fullName)) {
			self.warnings.push('Warning: Skipped non-versioned Flow: ' + fileProperty.fullName);
			return false;
		} else if (majorApiVersion >= 44 && fileProperty.type === 'FlowDefinition') {
			self.warnings.push('Warning: Skipped unnecessary FlowDefinition: ' + fileProperty.fullName);
			return false;
		}
		return true;
	});
	return self;
};


<?php

namespace OAuth2\ResponseType;

interface ResponseTypeInterface
{
    public function getAuthorizeResponse($params, $user_id = null);
}


<?xml version="1.0" encoding="utf-8"?>
<ProjectSchemaDefinitions xmlns="clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework">
  <Rule Name="libbitcoin-consensus-linkage-uiextension" PageTemplate="tool" DisplayName="Local Dependencies" SwitchPrefix="/" Order="1">
    <Rule.Categories>
      <Category Name="libbitcoin-consensus" DisplayName="libbitcoin-consensus" />
    </Rule.Categories>
    <Rule.DataSource>
      <DataSource Persistence="ProjectFile" ItemType="" />
    </Rule.DataSource>
    <EnumProperty Name="Linkage-libbitcoin-consensus" DisplayName="Linkage" Description="How libbitcoin-consensus will be linked into the output of this project" Category="libbitcoin-consensus">
      <EnumValue Name="none" DisplayName="Not linked" />
      <EnumValue Name="dynamic" DisplayName="Dynamic (DLL)" />
      <EnumValue Name="static" DisplayName="Static (LIB)" />
      <EnumValue Name="ltcg" DisplayName="Static using link time compile generation (LTCG)" />
    </EnumProperty>
  </Rule>
</ProjectSchemaDefinitions>


# SPDX-License-Identifier: GPL-2.0+
#
# (C) Copyright 2000, 2001, 2002
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.

obj-y	:= zoom1.o