Initialisation d'événements sur la touche Escape pour fermer les dialogues.
9913
public static void initEscapeClosesDialogs() {
		final AWTEventListener awtEventListener = new AWTEventListener() {
			/** {@inheritDoc} */
			@Override
			public void eventDispatched(final AWTEvent event) {
				if (event instanceof KeyEvent
						&& ((KeyEvent) event).getKeyCode() == KeyEvent.VK_ESCAPE
						&& event.getID() == KeyEvent.KEY_PRESSED) {
					escapePressed();
				}
			}
		};
		Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.KEY_EVENT_MASK);
	}
1105920
public void trainSentence(Word2VecParam param, final List<VocabWord> sentence, double alpha,
                    List<Triple<Integer, Integer, Integer>> changed) {
        if (sentence != null && !sentence.isEmpty()) {
            for (int i = 0; i < sentence.size(); i++) {
                VocabWord vocabWord = sentence.get(i);
                if (vocabWord != null && vocabWord.getWord().endsWith("STOP")) {
                    nextRandom.set(nextRandom.get() * 25214903917L + 11);
                    skipGram(param, i, sentence, (int) nextRandom.get() % param.getWindow(), alpha, changed);
                }
            }
        }
    }
1297009
function Lexer(text, cfg) {
        var self = this;
        self.page = new Page(text);
        self.cursor = new Cursor();
        self.nodeFactory = this;
        this.cfg = cfg || {};
    }
1203800
def vectorize_dialogue(self, dialogue, safe=True):
        
        if safe:
            return vectorize_dialogue_safe(dialogue)
        else:
            return vectorize_dialogue_unsafe(dialogue)
541756
function addEventListeners() {
			ctrl.ngelt.on('wheel', wheelOnElt);
			ctrl.ngelt.on('computegrabbersizes', ctrl.updateSize);
//			ctrl.elt.addEventListener("wheel", function (event) {
//				boxesScrollServices.execAndApplyIfScrollable($scope, this, wheel, [event]);
//			}, {passive: true, capture: true});
			ctrl.ngsb.on("mouseout", mouseoutOnSb);
			ctrl.ngsb.on("mousedown", mousedownOnSb); // sur le mousedown, si dans le grabber, on init le mode drag, sinon on inc/dec les pages tant que l'on est appuyé
			ctrl.ngsb.on("mouseup", mouseup);  // on stop l'inc/dec des pages
			ctrl.ngsb.on("click", boxesScrollServices.stopEvent); // desactive la propagation entre autrepour eviter la fermeture des popup
			ctrl.ngelt.on("mousemove", mousemoveOnElt); // on définit la couleur du grabber
			if (!ctrl.ngelt.css('display') !== 'none') { // si c'est une popup, le resize de l'ecran ne joue pas
				ng.element($window).on("resize", updateSize);
			}
			$document.on("mousedown", mousedownOnDoc);
			$document.on("keydown", keydownOnOnDoc);
			$document.on("scroll", invalidSizes);
		}
593053
def main(args):
    
    json.dump(vars(args), open(os.path.join(args.output_dir, 'config.json'), 'w'))

    if args.gpu_id == -1:
        ctx = mx.cpu()
    else:
        ctx = mx.gpu(args.gpu_id)

    mx.random.seed(args.seed, ctx=ctx)

    if args.mode == 'train':
        train_dataset = read_dataset(args, 'train_file')
        val_dataset = read_dataset(args, 'test_file')

        vocab_path = os.path.join(args.output_dir, 'vocab.jsons')
        if os.path.exists(vocab_path):
            vocab = nlp.Vocab.from_json(open(vocab_path).read())
        else:
            vocab = build_vocab(train_dataset)
            with open(vocab_path, 'w') as fout:
                fout.write(vocab.to_json())
        glove = nlp.embedding.create(args.embedding, source=args.embedding_source)
        vocab.set_embedding(glove)

        train_data_loader = prepare_data_loader(args, train_dataset, vocab)
        val_data_loader = prepare_data_loader(args, val_dataset, vocab, test=True)

        model = NLIModel(len(vocab), args.embedding_size, args.hidden_size,
                         args.dropout, args.intra_attention)
        train_model(model, train_data_loader, val_data_loader, vocab.embedding, ctx, args)
    elif args.mode == 'test':
        model_args = argparse.Namespace(**json.load(
            open(os.path.join(args.model_dir, 'config.json'))))
        vocab = nlp.Vocab.from_json(
            open(os.path.join(args.model_dir, 'vocab.jsons')).read())
        val_dataset = read_dataset(args, 'test_file')
        val_data_loader = prepare_data_loader(args, val_dataset, vocab, test=True)
        model = NLIModel(len(vocab), model_args.embedding_size,
                         model_args.hidden_size, 0., model_args.intra_attention)
        model.load_parameters(os.path.join(
            args.model_dir, 'checkpoints', 'valid_best.params'), ctx=ctx)
        loss_func = gluon.loss.SoftmaxCrossEntropyLoss()
        logger.info('Test on {}'.format(args.test_file))
        loss, acc = test_model(model, val_data_loader, loss_func, ctx)
        logger.info('loss={:.4f} acc={:.4f}'.format(loss, acc))
339469
private void onSetComment(CfDef cfDef, Properties cfProperties, StringBuilder builder)
    {
        String comment = cfProperties.getProperty(CassandraConstants.COMMENT);
        if (comment != null)
        {
            if (builder != null)
            {
                String comment_Str = CQLTranslator.getKeyword(CassandraConstants.COMMENT);
                builder.append(comment_Str);
                builder.append(CQLTranslator.EQ_CLAUSE);
                builder.append(CQLTranslator.QUOTE_STR);
                builder.append(comment);
                builder.append(CQLTranslator.QUOTE_STR);
                builder.append(CQLTranslator.AND_CLAUSE);

            }
            else
            {
                cfDef.setComment(comment);
            }
        }
    }
247206
function encounter(mood) {

  //Sentence 1: The meeting
  const familiar_people = wordLib.getWords("familiar_people");
  const strange_people = wordLib.getWords("strange_people");
  const locations = wordLib.getWords("locations");

  const person = nu.chooseFrom(familiar_people.concat(strange_people));
  let location = nu.chooseFrom(wordLib.getWords("locations"));
  const preposition = location[0];
  location = location[1];

  const s1 = `You may meet ${person} ${preposition} ${location}.`;

  // Sentence 2: The discussion
  let discussions = wordLib.getWords("neutral_discussions");
  discussions.concat(wordLib.getWords(mood + "_discussions"));
  const feeling_nouns = wordLib.getWords(mood + "_feeling_nouns");
  const emotive_nouns = wordLib.getWords(mood + "_emotive_nouns");
  const conversation_topics = wordLib.getWords("conversation_topics");

  const discussion = nu.chooseFrom(discussions);
  const rnum = Math.floor(Math.random() * 10);

  let feeling;

  if (rnum <- 5) {
    feeling = nu.chooseFrom(feeling_nouns);
    feeling = "feelings of " + feeling;
  } else {
    feeling = nu.chooseFrom(emotive_nouns);
  }
  const topic = nu.chooseFrom(conversation_topics);

  let s2 = `${nu.an(discussion)} about ${topic} may lead to ${feeling}.`;
  s2 = nu.sentenceCase(s2);

  return `${s1} ${s2}`;
}
606128
function speakIt({ action }) {
    const { toSpeak } = action.payload

    // Remember: unlike Promises, which share a similar construction,
    // the observable function is not run until the Observable recieves
    // a subscribe() call.
    return new Observable(observer => {
      try {
        const say = require("say")
        say.speak(toSpeak, null, null, () => {
          observer.complete()
        })

        // An Observable allows for cancellation by returning a
        // cancellation function
        return () => {
          say.stop()
        }
      } catch (error) {
        log("-- speech synthesis not available --")
        observer.error()
      }
    })
  }
1171580
function prompt (data, key, prompt, done) {
  // skip prompts whose when condition is not met
  if (prompt.when && !evaluate(prompt.when, data)) {
    return done()
  }

  var promptDefault = prompt.default
  if (typeof prompt.default === 'function') {
    promptDefault = function () {
      return prompt.default.bind(this)(data)
    }
  }

  inquirer.prompt([{
    type: promptMapping[prompt.type] || prompt.type,
    name: key,
    message: prompt.message || prompt.label || key,
    default: promptDefault,
    choices: prompt.choices || [],
    validate: prompt.validate || function () { return true }
  }], function (answers) {
    if (Array.isArray(answers[key])) {
      data[key] = {}
      answers[key].forEach(function (multiChoiceAnswer) {
        data[key][multiChoiceAnswer] = true
      })
    } else if (typeof answers[key] === 'string') {
      data[key] = answers[key].replace(/"/g, '\\"')
    } else {
      data[key] = answers[key]
    }
    done()
  })
}
383350
private void trainOnOneSample(Instance instance, int partialTreeIter, int i, int dataCount, CompletionService<ArrayList<BeamElement>> pool) throws InterruptedException, ExecutionException
    {
        boolean isPartial = instance.isPartial(options.rootFirst);

        if (partialTreeIter > i && isPartial)
            return;

        Configuration initialConfiguration = new Configuration(instance.getSentence(), options.rootFirst);
        Configuration firstOracle = initialConfiguration.clone();
        ArrayList<Configuration> beam = new ArrayList<Configuration>(options.beamWidth);
        beam.add(initialConfiguration);

        /**
         * The float is the oracle's cost
         * For more information see:
         * Yoav Goldberg and Joakim Nivre. "Training Deterministic Parsers with Non-Deterministic Oracles."
         * TACL 1 (2013): 403-414.
         * for the mean while we just use zero-cost oracles
         */
        Collection<Configuration> oracles = new HashSet<Configuration>();

        oracles.add(firstOracle);

        /**
         * For keeping track of the violations
         * For more information see:
         * Liang Huang, Suphan Fayong and Yang Guo. "Structured perceptron with inexact search."
         * In Proceedings of the 2012 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies,
         * pp. 142-151. Association for Computational Linguistics, 2012.
         */
        float maxViol = Float.NEGATIVE_INFINITY;
        Pair<Configuration, Configuration> maxViolPair = null;

        Configuration bestScoringOracle = null;
        boolean oracleInBeam = false;

        while (!ArcEager.isTerminal(beam) && beam.size() > 0)
        {
            /**
             *  generating new oracles
             *  it keeps the oracles which are in the terminal state
             */
            Collection<Configuration> newOracles = new HashSet<Configuration>();

            if (options.useDynamicOracle || isPartial)
            {
                bestScoringOracle = zeroCostDynamicOracle(instance, oracles, newOracles);
            }
            else
            {
                bestScoringOracle = staticOracle(instance, oracles, newOracles);
            }
            // try explore non-optimal transitions

            if (newOracles.size() == 0)
            {
//                System.err.println("...no oracle(" + dataCount + ")...");
                bestScoringOracle = staticOracle(instance, oracles, newOracles);
            }
            oracles = newOracles;

            TreeSet<BeamElement> beamPreserver = new TreeSet<BeamElement>();

            if (options.numOfThreads == 1 || beam.size() == 1)
            {
                beamSortOneThread(beam, beamPreserver);
            }
            else
            {
                for (int b = 0; b < beam.size(); b++)
                {
                    pool.submit(new BeamScorerThread(false, classifier, beam.get(b),
                                                     dependencyRelations, featureLength, b, options.rootFirst));
                }
                for (int b = 0; b < beam.size(); b++)
                {
                    for (BeamElement element : pool.take().get())
                    {
                        beamPreserver.add(element);
                        if (beamPreserver.size() > options.beamWidth)
                            beamPreserver.pollFirst();
                    }
                }
            }

            if (beamPreserver.size() == 0 || beam.size() == 0)
            {
                break;
            }
            else
            {
                oracleInBeam = false;

                ArrayList<Configuration> repBeam = new ArrayList<Configuration>(options.beamWidth);
                for (BeamElement beamElement : beamPreserver.descendingSet())
                {
//                    if (repBeam.size() >= options.beamWidth) // 只要beamWidth个configuration（这句是多余的）
//                        break;
                    int b = beamElement.index;
                    int action = beamElement.action;
                    int label = beamElement.label;
                    float score = beamElement.score;

                    Configuration newConfig = beam.get(b).clone();

                    ArcEager.commitAction(action, label, score, dependencyRelations, newConfig);
                    repBeam.add(newConfig);

                    if (!oracleInBeam && oracles.contains(newConfig))
                        oracleInBeam = true;
                }
                beam = repBeam;

                if (beam.size() > 0 && oracles.size() > 0)
                {
                    Configuration bestConfig = beam.get(0);
                    if (oracles.contains(bestConfig)) // 模型认为的最大分值configuration是zero cost
                    {
                        oracles = new HashSet<Configuration>();
                        oracles.add(bestConfig);
                    }
                    else // 否则
                    {
                        if (options.useRandomOracleSelection) // 随机选择一个 oracle
                        { // choosing randomly, otherwise using latent structured Perceptron
                            List<Configuration> keys = new ArrayList<Configuration>(oracles);
                            Configuration randomKey = keys.get(randGen.nextInt(keys.size()));
                            oracles = new HashSet<Configuration>();
                            oracles.add(randomKey);
                            bestScoringOracle = randomKey;
                        }
                        else // 选择 oracle中被模型认为分值最大的那个
                        {
                            oracles = new HashSet<Configuration>();
                            oracles.add(bestScoringOracle);
                        }
                    }

                    // do early update
                    if (!oracleInBeam && updateMode.equals("early"))
                        break;

                    // keep violations
                    if (!oracleInBeam && updateMode.equals("max_violation"))
                    {
                        float violation = bestConfig.getScore(true) - bestScoringOracle.getScore(true);//Math.abs(beam.get(0).getScore(true) - bestScoringOracle.getScore(true));
                        if (violation > maxViol)
                        {
                            maxViol = violation;
                            maxViolPair = new Pair<Configuration, Configuration>(bestConfig, bestScoringOracle);
                        }
                    }
                }
                else
                    break;
            }
        }

        // updating weights
        if (!oracleInBeam ||
                !bestScoringOracle.equals(beam.get(0)) // 虽然oracle在beam里面，但在最后时刻，它的得分不是最高
                )
        {
            updateWeights(initialConfiguration, maxViol, isPartial, bestScoringOracle, maxViolPair, beam);
        }
    }
1177819
def quote(bot, mask, target, args):
    
    msg = ' '.join(args['<args>'])
    bot.log.info('quote> %r', msg)
    bot.send(msg)
1193768
@Override
	public void initialize(Interval annotation) {
		
		// Si l'annotation est nulle : on sort
		if(annotation == null) return;
		
		// On rcupre la valeur minimum de l'annotation
		min = annotation.min();
		
		// On rcupre la valeur maximum de l'annotation
		max = annotation.max();
	}
25294
def on_batch_begin(self, last_input, last_target, **kwargs):
        ""
        if self.clip is not None:
            for p in self.critic.parameters(): p.data.clamp_(-self.clip, self.clip)
        return {'last_input':last_input,'last_target':last_target} if self.gen_mode else {'last_input':last_target,'last_target':last_input}
872451
function(content, opts, onOk, onCancel) {
        Dialog.setup('confirm', content, opts, onOk, onCancel);
      }
1256536
def main():
    """"""
    if len(argv) < 2:
        targetfile = 'target.y'
    else:
        targetfile = argv[1]
    print 'Parsing ruleset: ' + targetfile,
    flex_a = Flexparser()
    mma = flex_a.yyparse(targetfile)
    print 'OK'
    print 'Perform minimization on initial automaton:',
    mma.minimize()
    print 'OK'
    print 'Perform StateRemoval on minimal automaton:',
    state_removal = StateRemoval(mma)
    mma_regex = state_removal.get_regex()
    print mma_regex
605053
function Menu(arg,opt) {
        
        if ($.isPlainObject(arg) || Array.isArray(arg)) { opt = arg; arg = null; }
        
        /**
         * Conteneur du menu contextuel
         */
        if (!arg) arg = document.createElement('ul');
        
        if (arg) this.container = $(arg)[0];
        /**
         * Tableau d'objets MenuItem définissant la liste des éléments du menu
         */
        this.list = [];
        /**
         * Liste des séparateurs d'éléments
         */
        this.dividers = [];
        
        this.keyboardCtrls = new KeyboardCtrls(this);
        
        if (opt) this.set(opt); 
    }