TEST_F(HeaderTableTests, varyCapacity) {
  HPACKHeader accept("accept-encoding", "gzip");
  uint32_t max = 6;
  uint32_t capacity = accept.bytes() * max;
  HeaderTable table(capacity);

  // Fill the table (extra) and make sure we haven't violated our
  // size (bytes) limits (expected one entry to be evicted)
  for (size_t i = 0; i <= table.length(); ++i) {
    EXPECT_EQ(table.add(accept), true);
  }
  EXPECT_EQ(table.size(), max);

  // Size down the table and verify we are still honoring our size (bytes)
  // limits
  resizeAndFillTable(table, accept, 4, 5);

  // Size up the table (in between previous max and min within test) and verify
  // we are still horing our size (bytes) limits
  resizeAndFillTable(table, accept, 5, 6);

  // Finally reize up one last timestamps
  resizeAndFillTable(table, accept, 8, 9);
}


		onShow: function () {
			/* Remove preview */
			imgPreview.getElement().setHtml('');

			(t = this), (orgWidth = null), (orgHeight = null), (imgScal = 1), (lock = true);

			/* selected image or null */
			selectedImg = editor.getSelection();
			if (selectedImg) selectedImg = selectedImg.getSelectedElement();
			if (!selectedImg || selectedImg.getName() !== 'img') selectedImg = null;

			/* Set input values */
			t.setValueOf('tab-properties', 'lock', lock);
			t.setValueOf('tab-properties', 'vmargin', '0');
			t.setValueOf('tab-properties', 'hmargin', '0');
			t.setValueOf('tab-properties', 'border', '0');
			t.setValueOf('tab-properties', 'align', 'none');
			if (selectedImg) {
				/* Set input values from selected image */
				if (typeof selectedImg.getAttribute('width') == 'string') orgWidth = selectedImg.getAttribute('width');
				if (typeof selectedImg.getAttribute('height') == 'string') orgHeight = selectedImg.getAttribute('height');
				if ((orgWidth == null || orgHeight == null) && selectedImg.$) {
					orgWidth = selectedImg.$.width;
					orgHeight = selectedImg.$.height;
				}
				if (orgWidth != null && orgHeight != null) {
					t.setValueOf('tab-properties', 'width', orgWidth);
					t.setValueOf('tab-properties', 'height', orgHeight);
					orgWidth = parseInt(orgWidth, 10);
					orgHeight = parseInt(orgHeight, 10);
					imgScal = 1;
					if (!isNaN(orgWidth) && !isNaN(orgHeight) && orgHeight > 0 && orgWidth > 0) imgScal = orgWidth / orgHeight;
					if (imgScal <= 0) imgScal = 1;
				}

				if (typeof selectedImg.getAttribute('src') == 'string') {
					if (selectedImg.getAttribute('src').indexOf('data:') === 0) {
						imagePreview('base64');
						imagePreviewLoad(selectedImg.getAttribute('src'));
					}
				}
				if (typeof selectedImg.getAttribute('alt') == 'string')
					t.setValueOf('tab-properties', 'alt', selectedImg.getAttribute('alt'));
				if (typeof selectedImg.getAttribute('hspace') == 'string')
					t.setValueOf('tab-properties', 'hmargin', selectedImg.getAttribute('hspace'));
				if (typeof selectedImg.getAttribute('vspace') == 'string')
					t.setValueOf('tab-properties', 'vmargin', selectedImg.getAttribute('vspace'));
				if (typeof selectedImg.getAttribute('border') == 'string')
					t.setValueOf('tab-properties', 'border', selectedImg.getAttribute('border'));
				if (typeof selectedImg.getAttribute('align') == 'string') {
					switch (selectedImg.getAttribute('align')) {
						case 'top':
						case 'text-top':
							t.setValueOf('tab-properties', 'align', 'top');
							break;
						case 'baseline':
						case 'bottom':
						case 'text-bottom':
							t.setValueOf('tab-properties', 'align', 'bottom');
							break;
						case 'left':
							t.setValueOf('tab-properties', 'align', 'left');
							break;
						case 'right':
							t.setValueOf('tab-properties', 'align', 'right');
							break;
					}
				}
				t.selectPage('tab-properties');
			}
		},


struct snd_seq_client_port *snd_seq_create_port(struct snd_seq_client *client,
						int port)
{
	unsigned long flags;
	struct snd_seq_client_port *new_port, *p;
	int num = -1;

	/* sanity check */
	if (snd_BUG_ON(!client))
		return NULL;

	if (client->num_ports >= SNDRV_SEQ_MAX_PORTS) {
		pr_warn("ALSA: seq: too many ports for client %d\n", client->number);
		return NULL;
	}

	/* create a new port */
	new_port = kzalloc(sizeof(*new_port), GFP_KERNEL);
	if (!new_port)
		return NULL;	/* failure, out of memory */
	/* init port data */
	new_port->addr.client = client->number;
	new_port->addr.port = -1;
	new_port->owner = THIS_MODULE;
	sprintf(new_port->name, "port-%d", num);
	snd_use_lock_init(&new_port->use_lock);
	port_subs_info_init(&new_port->c_src);
	port_subs_info_init(&new_port->c_dest);

	num = port >= 0 ? port : 0;
	mutex_lock(&client->ports_mutex);
	write_lock_irqsave(&client->ports_lock, flags);
	list_for_each_entry(p, &client->ports_list_head, list) {
		if (p->addr.port > num)
			break;
		if (port < 0) /* auto-probe mode */
			num = p->addr.port + 1;
	}
	/* insert the new port */
	list_add_tail(&new_port->list, &p->list);
	client->num_ports++;
	new_port->addr.port = num;	/* store the port number in the port */
	write_unlock_irqrestore(&client->ports_lock, flags);
	mutex_unlock(&client->ports_mutex);
	sprintf(new_port->name, "port-%d", num);

	return new_port;
}


	protected String getCorsDomain(String referer, String userAgent)
	{
		String dom = null;

		if (referer != null && referer.toLowerCase()
				.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
		{
			dom = referer.toLowerCase().substring(0,
					referer.indexOf(".draw.io/") + 8);
		}
		else if (referer != null && referer.toLowerCase()
				.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
		{
			dom = referer.toLowerCase().substring(0,
					referer.indexOf(".diagrams.net/") + 13);
		}
		else if (referer != null && referer.toLowerCase()
				.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
		{
			dom = referer.toLowerCase().substring(0,
					referer.indexOf(".quipelements.com/") + 17);
		}
		// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
		// UA refers to old FF on macOS so low risk and fixes requests from existing servers
		else if ((referer != null
				&& referer.equals("draw.io Proxy Confluence Server"))
				|| (userAgent != null && userAgent.equals(
						"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
		{
			dom = "";
		}

		return dom;
	}


printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
           labellist *ll, const char *msg)
{
    int i, ibit, iarc;
    ss_state *yy;
    ss_arc *zz;

    printf("Subset DFA %s\n", msg);
    for (i = 0; i < xx_nstates; i++) {
        yy = &xx_state[i];
        if (yy->ss_deleted)
            continue;
        printf(" Subset %d", i);
        if (yy->ss_finish)
            printf(" (finish)");
        printf(" { ");
        for (ibit = 0; ibit < nbits; ibit++) {
            if (testbit(yy->ss_ss, ibit))
                printf("%d ", ibit);
        }
        printf("}\n");
        for (iarc = 0; iarc < yy->ss_narcs; iarc++) {
            zz = &yy->ss_arc[iarc];
            printf("  Arc to state %d, label %s\n",
                zz->sa_arrow,
                Ta3Grammar_LabelRepr(
                    &ll->ll_label[zz->sa_label]));
        }
    }
}


static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer)
{
	struct k_itimer *timr;
	unsigned long flags;
	int si_private = 0;
	enum hrtimer_restart ret = HRTIMER_NORESTART;

	timr = container_of(timer, struct k_itimer, it.real.timer);
	spin_lock_irqsave(&timr->it_lock, flags);

	timr->it_active = 0;
	if (timr->it_interval != 0)
		si_private = ++timr->it_requeue_pending;

	if (posix_timer_event(timr, si_private)) {
		/*
		 * signal was not sent because of sig_ignor
		 * we will not get a call back to restart it AND
		 * it should be restarted.
		 */
		if (timr->it_interval != 0) {
			ktime_t now = hrtimer_cb_get_time(timer);

			/*
			 * FIXME: What we really want, is to stop this
			 * timer completely and restart it in case the
			 * SIG_IGN is removed. This is a non trivial
			 * change which involves sighand locking
			 * (sigh !), which we don't want to do late in
			 * the release cycle.
			 *
			 * For now we just let timers with an interval
			 * less than a jiffie expire every jiffie to
			 * avoid softirq starvation in case of SIG_IGN
			 * and a very small interval, which would put
			 * the timer right back on the softirq pending
			 * list. By moving now ahead of time we trick
			 * hrtimer_forward() to expire the timer
			 * later, while we still maintain the overrun
			 * accuracy, but have some inconsistency in
			 * the timer_gettime() case. This is at least
			 * better than a starved softirq. A more
			 * complex fix which solves also another related
			 * inconsistency is already in the pipeline.
			 */
#ifdef CONFIG_HIGH_RES_TIMERS
			{
				ktime_t kj = NSEC_PER_SEC / HZ;

				if (timr->it_interval < kj)
					now = ktime_add(now, kj);
			}
#endif
			timr->it_overrun += hrtimer_forward(timer, now,
							    timr->it_interval);
			ret = HRTIMER_RESTART;
			++timr->it_requeue_pending;
			timr->it_active = 1;
		}
	}

	unlock_timer(timr, flags);
	return ret;
}


static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
{
	struct bfq_data *bfqd = bfqq->bfqd;
	enum bfqq_expiration reason;
	unsigned long flags;

	spin_lock_irqsave(&bfqd->lock, flags);
	bfq_clear_bfqq_wait_request(bfqq);

	if (bfqq != bfqd->in_service_queue) {
		spin_unlock_irqrestore(&bfqd->lock, flags);
		return;
	}

	if (bfq_bfqq_budget_timeout(bfqq))
		/*
		 * Also here the queue can be safely expired
		 * for budget timeout without wasting
		 * guarantees
		 */
		reason = BFQQE_BUDGET_TIMEOUT;
	else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
		/*
		 * The queue may not be empty upon timer expiration,
		 * because we may not disable the timer when the
		 * first request of the in-service queue arrives
		 * during disk idling.
		 */
		reason = BFQQE_TOO_IDLE;
	else
		goto schedule_dispatch;

	bfq_bfqq_expire(bfqd, bfqq, true, reason);

schedule_dispatch:
	spin_unlock_irqrestore(&bfqd->lock, flags);
	bfq_schedule_dispatch(bfqd);


int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
    int j, loops = server.cronloops++;
    REDIS_NOTUSED(eventLoop);
    REDIS_NOTUSED(id);
    REDIS_NOTUSED(clientData);

    /* We take a cached value of the unix time in the global state because
     * with virtual memory and aging there is to store the current time
     * in objects at every object access, and accuracy is not needed.
     * To access a global var is faster than calling time(NULL) */
    server.unixtime = time(NULL);
    /* We have just 22 bits per object for LRU information.
     * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
     * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
     *
     * Note that even if this will wrap after 1.5 years it's not a problem,
     * everything will still work but just some object will appear younger
     * to Redis. But for this to happen a given object should never be touched
     * for 1.5 years.
     *
     * Note that you can change the resolution altering the
     * REDIS_LRU_CLOCK_RESOLUTION define.
     */
    updateLRUClock();

    /* We received a SIGTERM, shutting down here in a safe way, as it is
     * not ok doing so inside the signal handler. */
    if (server.shutdown_asap) {
        if (prepareForShutdown() == REDIS_OK) exit(0);
        redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
    }

    /* Show some info about non-empty databases */
    for (j = 0; j < server.dbnum; j++) {
        long long size, used, vkeys;

        size = dictSlots(server.db[j].dict);
        used = dictSize(server.db[j].dict);
        vkeys = dictSize(server.db[j].expires);
        if (!(loops % 50) && (used || vkeys)) {
            redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
            /* dictPrintStats(server.dict); */
        }
    }

    /* We don't want to resize the hash tables while a bacground saving
     * is in progress: the saving child is created using fork() that is
     * implemented with a copy-on-write semantic in most modern systems, so
     * if we resize the HT while there is the saving child at work actually
     * a lot of memory movements in the parent will cause a lot of pages
     * copied. */
    if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
        if (!(loops % 10)) tryResizeHashTables();
        if (server.activerehashing) incrementallyRehash();
    }

    /* Show information about connected clients */
    if (!(loops % 50)) {
        redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
            listLength(server.clients)-listLength(server.slaves),
            listLength(server.slaves),
            zmalloc_used_memory());
    }

    /* Close connections of timedout clients */
    if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
        closeTimedoutClients();

    /* Check if a background saving or AOF rewrite in progress terminated */
    if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
        int statloc;
        pid_t pid;

        if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
            if (pid == server.bgsavechildpid) {
                backgroundSaveDoneHandler(statloc);
            } else {
                backgroundRewriteDoneHandler(statloc);
            }
            updateDictResizePolicy();
        }
    } else {
        /* If there is not a background saving in progress check if
         * we have to save now */
         time_t now = time(NULL);
         for (j = 0; j < server.saveparamslen; j++) {
            struct saveparam *sp = server.saveparams+j;

            if (server.dirty >= sp->changes &&
                now-server.lastsave > sp->seconds) {
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, sp->seconds);
                rdbSaveBackground(server.dbfilename);
                break;
            }
         }
    }

    /* Expire a few keys per cycle, only if this is a master.
     * On slaves we wait for DEL operations synthesized by the master
     * in order to guarantee a strict consistency. */
    if (server.masterhost == NULL) activeExpireCycle();

    /* Remove a few cached objects from memory if we are over the
     * configured memory limit */
    while (server.ds_enabled && zmalloc_used_memory() >
            server.cache_max_memory)
    {
        cacheFreeOneEntry();
    }

    /* Replication cron function -- used to reconnect to master and
     * to detect transfer failures. */
    if (!(loops % 10)) replicationCron();

    return 100;
}


static int pop_sync_mailbox (CONTEXT *ctx, int *index_hint)
{
  int i, j, ret = 0;
  char buf[LONG_STRING];
  POP_DATA *pop_data = (POP_DATA *)ctx->data;
  progress_t progress;
#ifdef USE_HCACHE
  header_cache_t *hc = NULL;
#endif

  pop_data->check_time = 0;

  FOREVER
  {
    if (pop_reconnect (ctx) < 0)
      return -1;

    mutt_progress_init (&progress, _("Marking messages deleted..."),
			MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);

#if USE_HCACHE
    hc = pop_hcache_open (pop_data, ctx->path);
#endif

    for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
    {
      if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
      {
	j++;
	if (!ctx->quiet)
	  mutt_progress_update (&progress, j, -1);
	snprintf (buf, sizeof (buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
	if ((ret = pop_query (pop_data, buf, sizeof (buf))) == 0)
	{
	  mutt_bcache_del (pop_data->bcache, cache_id (ctx->hdrs[i]->data));
#if USE_HCACHE
	  mutt_hcache_delete (hc, ctx->hdrs[i]->data, strlen);
#endif
	}
      }

#if USE_HCACHE
      if (ctx->hdrs[i]->changed)
      {
	mutt_hcache_store (hc, ctx->hdrs[i]->data, ctx->hdrs[i], 0, strlen, MUTT_GENERATE_UIDVALIDITY);
      }
#endif

    }

#if USE_HCACHE
    mutt_hcache_close (hc);
#endif

    if (ret == 0)
    {
      strfcpy (buf, "QUIT\r\n", sizeof (buf));
      ret = pop_query (pop_data, buf, sizeof (buf));
    }

    if (ret == 0)
    {
      pop_data->clear_cache = 1;
      pop_clear_cache (pop_data);
      pop_data->status = POP_DISCONNECTED;
      return 0;
    }

    if (ret == -2)
    {
      mutt_error ("%s", pop_data->err_msg);
      mutt_sleep (2);
      return -1;
    }
  }
}


	public static AlgorithmMode resolveAlgorithmMode(final JWEAlgorithm alg)
		throws JOSEException {

		if (alg.equals(JWEAlgorithm.ECDH_ES)) {

			return AlgorithmMode.DIRECT;

		} else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW) ||
			alg.equals(JWEAlgorithm.ECDH_ES_A192KW) ||
			alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) {

			return AlgorithmMode.KW;
		} else {

			throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(
				alg,
				ECDHCryptoProvider.SUPPORTED_ALGORITHMS));
		}
	}


static void process_tree(struct rev_info *revs,
			 struct tree *tree,
			 show_object_fn show,
			 struct strbuf *base,
			 const char *name,
			 void *cb_data)
{
	struct object *obj = &tree->object;
	struct tree_desc desc;
	struct name_entry entry;
	enum interesting match = revs->diffopt.pathspec.nr == 0 ?
		all_entries_interesting: entry_not_interesting;
	int baselen = base->len;

	if (!revs->tree_objects)
		return;
	if (!obj)
		die("bad tree object");
	if (obj->flags & (UNINTERESTING | SEEN))
		return;
	if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {
		if (revs->ignore_missing_links)
			return;
		die("bad tree object %s", oid_to_hex(&obj->oid));
	}

	obj->flags |= SEEN;
	strbuf_addstr(base, name);
	show(obj, base->buf, cb_data);
	if (base->len)
		strbuf_addch(base, '/');

	init_tree_desc(&desc, tree->buffer, tree->size);

	while (tree_entry(&desc, &entry)) {
		if (match != all_entries_interesting) {
			match = tree_entry_interesting(&entry, base, 0,
						       &revs->diffopt.pathspec);
			if (match == all_entries_not_interesting)
				break;
			if (match == entry_not_interesting)
				continue;
		}

		if (S_ISDIR(entry.mode))
			process_tree(revs,
				     lookup_tree(entry.sha1),
				     show, base, entry.path,
				     cb_data);
		else if (S_ISGITLINK(entry.mode))
			process_gitlink(revs, entry.sha1,
					show, base, entry.path,
					cb_data);
		else
			process_blob(revs,
				     lookup_blob(entry.sha1),
				     show, base, entry.path,
				     cb_data);
	}
	strbuf_setlen(base, baselen);
	free_tree_buffer(tree);
}


0),!1,null,0,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,.5*v));return c};Ka.prototype.getConstraints=function(c,l,x){c=[];var p=Math.max(0,Math.min(l,parseFloat(mxUtils.getValue(this.style,"dx",this.dx)))),v=Math.max(0,Math.min(x,parseFloat(mxUtils.getValue(this.style,"dy",this.dy))));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1));c.push(new mxConnectionConstraint(new mxPoint(.5,0),!1));c.push(new mxConnectionConstraint(new mxPoint(1,0),!1));c.push(new mxConnectionConstraint(new mxPoint(0,
0),!1,null,l,.5*v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,l,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*(l+p),v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,.5*(x+v)));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,x));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*p,x));c.push(new mxConnectionConstraint(new mxPoint(0,.5),!1));c.push(new mxConnectionConstraint(new mxPoint(0,
1),!1));return c};bb.prototype.constraints=[new mxConnectionConstraint(new mxPoint(0,0),!1),new mxConnectionConstraint(new mxPoint(0,.5),!1),new mxConnectionConstraint(new mxPoint(0,1),!1),new mxConnectionConstraint(new mxPoint(.25,.5),!1),new mxConnectionConstraint(new mxPoint(.5,.5),!1),new mxConnectionConstraint(new mxPoint(.75,.5),!1),new mxConnectionConstraint(new mxPoint(1,0),!1),new mxConnectionConstraint(new mxPoint(1,.5),!1),new mxConnectionConstraint(new mxPoint(1,1),!1)];Za.prototype.getConstraints=


  public synchronized MultiMap headers() {
    if (headers == null) {
      headers = new CaseInsensitiveHeaders();
    }
    return headers;
  }


  constructor({ log, port }: { log: LogEntry; port?: number }) {
    this.log = log
    this.debugLog = this.log.placeholder({ level: LogLevel.debug, childEntriesInheritLevel: true })
    this.garden = undefined
    this.port = port
    this.authKey = randomString(64)
    this.incomingEvents = new EventBus()
    this.activePersistentRequests = {}

    this.serversUpdatedListener = ({ servers }) => {
      // Update status log line with new `garden dashboard` server, if any
      for (const { host, command } of servers) {
        if (command === "dashboard") {
          this.showUrl(host)
          return
        }
      }

      // No active explicit dashboard processes, show own URL instead
      this.showUrl(this.getUrl())
    }
  }


	public function __construct() {
		parent::__construct();

		$this->setDefaults();
	}


  def tryLoginAsMember(loginAttempt: MemberLoginAttempt): Hopefully[MemberLoginGrant] = {
    SECURITY; COULD // add setting that prevents people from logging in by username — because the
    // username is public, can starting guessing passwords directly. (There are rate limits.) Sth like:
    // if (!settings.allowLoginByUsername && loginAttempt.isByUsername) throwForbidden(...)
    // + prevent submitting username, client side.

    val settings = getWholeSiteSettings()
    dieIf(loginAttempt.isInstanceOf[PasswordLoginAttempt] &&
        !settings.canLoginWithPassword, "TyE0PWDLGI602")
    dieIf(loginAttempt.isInstanceOf[OpenAuthLoginAttempt] && settings.enableSso,
        "TyESSO0OAU02")

    val loginGrant = readWriteTransaction { tx =>
      val loginGrant: MemberLoginGrant =
            tx.tryLoginAsMember(loginAttempt, requireVerifiedEmail =
                  settings.requireVerifiedEmail) getOrIfBad { problem =>
              return Bad(problem)
            }

      addUserStats(UserStats(loginGrant.user.id, lastSeenAt = tx.now))(tx)

      // What? isSuspendedAt checks only suspendedTill ? what about suspendedAt? [4ELBAUPW2]
      // (Fine for now, maybe need to fix later though)
      if (!loginGrant.user.isSuspendedAt(loginAttempt.date))
        return Good(loginGrant)

      val user = tx.loadUserInclDetails(loginGrant.user.id) getOrElse throwForbidden(
        "DwE05KW2", "User not found, id: " + loginGrant.user.id)
      // Still suspended?
      if (user.suspendedAt.isDefined) {
        val forHowLong = user.suspendedTill match {
          case None => "forever"
          case Some(date) => "until " + toIso8601NoT(date)
        }
        throwForbidden("TyEUSRSSPNDD_", o"""Account suspended $forHowLong,
            reason: ${user.suspendedReason getOrElse "?"}""")
      }

      // Not suspended, is past end date.
      loginGrant
    }

    // Don't save any site cache version, because user specific data doesn't change
    // when site specific data changes.
    memCache.put(
          patKey(loginGrant.user.id),
          MemCacheValueIgnoreVersion(loginGrant.user))

    Good(loginGrant)
  }

  def logout(pat: Pat, bumpLastSeen: Bo): U = {


func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {
	r := &envoy_config_route_v3.Route{
		Name: "pomerium-path-" + path,
		Match: &envoy_config_route_v3.RouteMatch{
			PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
		},
		Action: &envoy_config_route_v3.Route_Route{
			Route: &envoy_config_route_v3.RouteAction{
				ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
					Cluster: httpCluster,
				},
			},
		},
	}
	if !protected {
		r.TypedPerFilterConfig = map[string]*any.Any{
			"envoy.filters.http.ext_authz": disableExtAuthz,
		}
	}
	return r, nil
}


        def print_train_stats():
            print(
                "TEMPLATE STATISTICS (TRAIN)  {} templates, {} rules)".format(
                    len(template_counts), len(tids)
                )
            )
            print(
                "TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} "
                "final: {finalerrors:5d} {finalacc:.4f} ".format(**train_stats)
            )
            head = "#ID | Score (train) |  #Rules     | Template"
            print(head, "\n", "-" * len(head), sep="")
            train_tplscores = sorted(
                weighted_traincounts.items(), key=det_tplsort, reverse=True
            )
            for (tid, trainscore) in train_tplscores:
                s = "{} | {:5d}   {:5.3f} |{:4d}   {:.3f} | {}".format(
                    tid,
                    trainscore,
                    trainscore / tottrainscores,
                    template_counts[tid],
                    template_counts[tid] / len(tids),
                    Template.ALLTEMPLATES[int(tid)],
                )
                print(s)


    public void emptyHeadersShouldBeEqual() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        final HttpHeadersBase headers2 = newEmptyHeaders();
        assertThat(headers2).isEqualTo(headers1);
        assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());
    }


void	cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)						{cJSON_AddItemToArray(array,create_reference(item));}


def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attri in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__')


            foreach ($this->fixesForLevel[$level] as $fix) {
                $ret[$fix] = true;
            }


export function escape(value: unknown, is_attr = false) {
	const str = String(value);

	const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
	pattern.lastIndex = 0;

	let escaped = '';
	let last = 0;

  while (pattern.test(str)) {
    const i = pattern.lastIndex - 1;
    const ch = str[i];
    escaped += str.substring(last, i) + (ch === '&' ? '&' : (ch === '"' ? '"' : '<'));
    last = i + 1;
  }

	return escaped + str.substring(last);
}


static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
		unsigned long end, int write, struct page **pages, int *nr)
{
	struct page *head, *page;
	int refs;

	if (!pud_access_permitted(orig, write))
		return 0;

	if (pud_devmap(orig))
		return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);

	refs = 0;
	page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
	do {
		pages[*nr] = page;
		(*nr)++;
		page++;
		refs++;
	} while (addr += PAGE_SIZE, addr != end);

	head = compound_head(pud_page(orig));
	if (!page_cache_add_speculative(head, refs)) {
		*nr -= refs;
		return 0;
	}

	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
		*nr -= refs;
		while (refs--)
			put_page(head);
		return 0;
	}

	SetPageReferenced(head);
	return 1;
}


TfLiteStatus LessEval(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteTensor* input1;
  TF_LITE_ENSURE_OK(context,
                    GetInputSafe(context, node, kInputTensor1, &input1));
  const TfLiteTensor* input2;
  TF_LITE_ENSURE_OK(context,
                    GetInputSafe(context, node, kInputTensor2, &input2));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));
  bool requires_broadcast = !HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteFloat32:
      Comparison<float, reference_ops::LessFn>(input1, input2, output,
                                               requires_broadcast);
      break;
    case kTfLiteInt32:
      Comparison<int32_t, reference_ops::LessFn>(input1, input2, output,
                                                 requires_broadcast);
      break;
    case kTfLiteInt64:
      Comparison<int64_t, reference_ops::LessFn>(input1, input2, output,
                                                 requires_broadcast);
      break;
    case kTfLiteUInt8:
      ComparisonQuantized<uint8_t, reference_ops::LessFn>(
          input1, input2, output, requires_broadcast);
      break;
    case kTfLiteInt8:
      ComparisonQuantized<int8_t, reference_ops::LessFn>(input1, input2, output,
                                                         requires_broadcast);
      break;
    default:
      context->ReportError(context,
                           "Does not support type %d, requires float|int|uint8",
                           input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}


    public function search_external() {
//        global $db, $user;
        global $db;

        $sql = "select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "external_addresses as a "; //R JOIN " .
        //$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
        $sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
            "*' IN BOOLEAN MODE) ";
        $sql .= "order by match (a.firstname,a.lastname,a.email,a.organization)  against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
        $res = $db->selectObjectsBySql($sql);
        foreach ($res as $key=>$record) {
            $res[$key]->title = $record->firstname . ' ' . $record->lastname;
        }
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    protected function deleteFileInStorage(Attachment $attachment)
    {
        $storage = $this->getStorage();
        $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));

        $storage->delete($this->adjustPathForStorageDisk($attachment->path));
        if (count($storage->allFiles($dirPath)) === 0) {
            $storage->deleteDirectory($dirPath);
        }
    }


void luaD_call (lua_State *L, StkId func, int nresults) {
  lua_CFunction f;
 retry:
  switch (ttypetag(s2v(func))) {
    case LUA_VCCL:  /* C closure */
      f = clCvalue(s2v(func))->f;
      goto Cfunc;
    case LUA_VLCF:  /* light C function */
      f = fvalue(s2v(func));
     Cfunc: {
      int n;  /* number of returns */
      CallInfo *ci = next_ci(L);
      checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
      ci->nresults = nresults;
      ci->callstatus = CIST_C;
      ci->top = L->top + LUA_MINSTACK;
      ci->func = func;
      L->ci = ci;
      lua_assert(ci->top <= L->stack_last);
      if (L->hookmask & LUA_MASKCALL) {
        int narg = cast_int(L->top - func) - 1;
        luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
      }
      lua_unlock(L);
      n = (*f)(L);  /* do the actual call */
      lua_lock(L);
      api_checknelems(L, n);
      luaD_poscall(L, ci, n);
      break;
    }
    case LUA_VLCL: {  /* Lua function */
      CallInfo *ci = next_ci(L);
      Proto *p = clLvalue(s2v(func))->p;
      int narg = cast_int(L->top - func) - 1;  /* number of real arguments */
      int nfixparams = p->numparams;
      int fsize = p->maxstacksize;  /* frame size */
      checkstackp(L, fsize, func);
      ci->nresults = nresults;
      ci->u.l.savedpc = p->code;  /* starting point */
      ci->callstatus = 0;
      ci->top = func + 1 + fsize;
      ci->func = func;
      L->ci = ci;
      for (; narg < nfixparams; narg++)
        setnilvalue(s2v(L->top++));  /* complete missing arguments */
      lua_assert(ci->top <= L->stack_last);
      luaV_execute(L, ci);  /* run the function */
      break;
    }
    default: {  /* not a function */
      checkstackp(L, 1, func);  /* space for metamethod */
      luaD_tryfuncTM(L, func);  /* try to get '__call' metamethod */
      goto retry;  /* try again with metamethod */
    }
  }
}


    constructor() {
        super();
        this._aborted = 0;
        this._helloReceived = false;

        // before HEL/ACK
        this.maxChunkCount = 1;
        this.maxMessageSize = 4 * 1024;
        this.receiveBufferSize = 4 * 1024;
    }


      it 'should return tokens' do
        @store.flush_tokens

        tokens = @store.allowed_tokens
        tokens.length.should == 1
        tokens.should == @store.allowed_tokens

        Time.travel(Time.now + 1) do
          new_tokens = @store.allowed_tokens
          new_tokens.length.should == 1
          new_tokens.should == tokens
        end

        Time.travel(Time.now + Rack::MiniProfiler::AbstractStore::MAX_TOKEN_AGE + 1) do
          new_tokens = @store.allowed_tokens
          new_tokens.length.should == 2
          (new_tokens - tokens).length.should == 1
        end

      end


        public virtual Subscription PreviewChange(ChangeTimeframe timeframe)
        {
            if (!_saved)
            {
                throw new Recurly.RecurlyException("Must have an existing subscription to preview changes.");
            }

            Client.WriteXmlDelegate writeXmlDelegate;

            if (ChangeTimeframe.Renewal == timeframe)
                writeXmlDelegate = WriteChangeSubscriptionAtRenewalXml;
            else
                writeXmlDelegate = WriteChangeSubscriptionNowXml;

            var previewSubscription = new Subscription();

            var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Post,
                UrlPrefix + Uri.EscapeUriString(Uuid) + "/preview",
                writeXmlDelegate,
                previewSubscription.ReadPreviewXml);

            return statusCode == HttpStatusCode.NotFound ? null : previewSubscription;
        }


def resource_stop(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::WRITE)
    return 403, 'Permission denied'
  end
  stdout, stderr, retval = run_cmd(
    session, PCS, "resource", "disable", params[:resource]
  )
  if retval == 0
    return JSON.generate({"success" => "true"})
  else
    return JSON.generate({"error" => "true", "stdout" => stdout, "stderror" => stderr})
  end
end


    public function createFromBill(Request $request, Bill $bill)
    {
        $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_bill', ['name' => e($bill->name)]));

        $this->createDefaultRuleGroup();
        $this->createDefaultRule();
        $preFilled = [
            'strict'      => true,
            'title'       => (string)trans('firefly.new_rule_for_bill_title', ['name' => $bill->name]),
            'description' => (string)trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]),
        ];

        // make triggers and actions from the bill itself.

        // get triggers and actions for bill:
        $oldTriggers = $this->getTriggersForBill($bill);
        $oldActions  = $this->getActionsForBill($bill);

        $triggerCount = \count($oldTriggers);
        $actionCount  = \count($oldActions);
        $subTitleIcon = 'fa-clone';

        // title depends on whether or not there is a rule group:
        $subTitle = (string)trans('firefly.make_new_rule_no_group');

        // flash old data
        $request->session()->flash('preFilled', $preFilled);

        // put previous url in session if not redirect from store (not "create another").
        if (true !== session('rules.create.fromStore')) {
            $this->rememberPreviousUri('rules.create.uri');
        }
        session()->forget('rules.create.fromStore');

        return view(
            'rules.rule.create', compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle')
        );
    }


    public function mount(array $opts)
    {
        $creds = null;
        if (isset($opts['access_token'])) {
            $this->netMountKey = md5(join('-', array('googledrive', $opts['path'], (isset($opts['access_token']['refresh_token'])? $opts['access_token']['refresh_token'] : $opts['access_token']['access_token']))));
        }

        $client = new \Google_Client();
        $client->setClientId($opts['client_id']);
        $client->setClientSecret($opts['client_secret']);

        if (!empty($opts['access_token'])) {
            $client->setAccessToken($opts['access_token']);
        }
        if ($client->isAccessTokenExpired()) {
            try {
                $creds = $client->fetchAccessTokenWithRefreshToken();
            } catch (LogicException $e) {
                $this->session->remove('GoogleDriveAuthParams');
                throw $e;
            }
        }

        $service = new \Google_Service_Drive($client);

        // If path is not set, use the root
        if (!isset($opts['path']) || $opts['path'] === '') {
            $opts['path'] = 'root';
        }

        $googleDrive = new GoogleDriveAdapter($service, $opts['path'], [ 'useHasDir' => true ]);

        $opts['fscache'] = null;
        if ($this->options['gdCacheDir'] && is_writeable($this->options['gdCacheDir'])) {
            if ($this->options['gdCacheExpire']) {
                $opts['fscache'] = new elFinderVolumeFlysystemGoogleDriveCache(new Local($this->options['gdCacheDir']), $this->options['gdCachePrefix'].$this->netMountKey, $this->options['gdCacheExpire']);
            }
        }
        if ($opts['fscache']) {
            $filesystem = new Filesystem(new CachedAdapter($googleDrive, $opts['fscache']));
        } else {
            $filesystem = new Filesystem($googleDrive);
        }

        $opts['driver'] = 'FlysystemExt';
        $opts['filesystem'] = $filesystem;
        $opts['separator'] = '/';
        $opts['checkSubfolders'] = true;
        if (! isset($opts['alias'])) {
            $opts['alias'] = 'GoogleDrive';
        }

        if ($res = parent::mount($opts)) {
            // update access_token of session data
            if ($creds) {
                $netVolumes = $this->session->get('netvolume');
                $netVolumes[$this->netMountKey]['access_token'] = array_merge($netVolumes[$this->netMountKey]['access_token'], $creds);
                $this->session->set('netvolume', $netVolumes);
            }
        }

        return $res;
    }


	public function setSectionSeparators( ?array $separators ) {
		$this->sectionSeparators = (array)$separators ?? [];
	}


decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
	size_t cipher_len;
	size_t i;
	unsigned char iv[16] = { 0 };
	unsigned char plaintext[4096] = { 0 };
	epass2003_exdata *exdata = NULL;

	if (!card->drv_data)
		return SC_ERROR_INVALID_ARGUMENTS;

	exdata = (epass2003_exdata *)card->drv_data;

	/* no cipher */
	if (in[0] == 0x99)
		return 0;

	/* parse cipher length */
	if (0x01 == in[2] && 0x82 != in[1]) {
		cipher_len = in[1];
		i = 3;
	}
	else if (0x01 == in[3] && 0x81 == in[1]) {
		cipher_len = in[2];
		i = 4;
	}
	else if (0x01 == in[4] && 0x82 == in[1]) {
		cipher_len = in[2] * 0x100;
		cipher_len += in[3];
		i = 5;
	}
	else {
		return -1;
	}

	if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
		return -1;

	/* decrypt */
	if (KEY_TYPE_AES == exdata->smtype)
		aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
	else
		des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);

	/* unpadding */
	while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
		cipher_len--;

	if (2 == cipher_len)
		return -1;

	memcpy(out, plaintext, cipher_len - 2);
	*out_len = cipher_len - 2;
	return 0;
}


static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg)
{
	struct usbdevfs_connectinfo ci;

	memset(&ci, 0, sizeof(ci));
	ci.devnum = ps->dev->devnum;
	ci.slow = ps->dev->speed == USB_SPEED_LOW;

	if (copy_to_user(arg, &ci, sizeof(ci)))
		return -EFAULT;
	return 0;
}


    public static function error ($vars="", $val='') {
        if( isset($vars) && $vars != "" ) {

            $file = GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php';
            if (file_exists($file)) {

                include($file);

            }

        }else{

            include(GX_PATH.'/inc/lib/Control/Error/unknown.control.php');

        }
    }


    public void newDocumentFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception
    {
        // new document = xwiki:X.Y
        DocumentReference documentReference =
            new DocumentReference("Y", new SpaceReference("X", new WikiReference("xwiki")));
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

        // Mock 1 existing template provider
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"),
            Arrays.asList("AnythingButX"));

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify that the create template is rendered, so the UI is displayed for the user to see the error.
        assertEquals("create", result);

        // Check that the exception is properly set in the context for the UI to display.
        XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException");
        assertNotNull(exception);
        assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode());

        // We should not get this far so no redirect should be done, just the template will be rendered.
        verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
            any(), any(XWikiContext.class));
    }


TEST_F(ClusterInfoImplTest, Http3) {
  const std::string yaml = TestEnvironment::substitute(R"EOF(
    name: name
    connect_timeout: 0.25s
    type: STRICT_DNS
    lb_policy: MAGLEV
    load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: foo.bar.com
                    port_value: 443
    transport_socket:
      name: envoy.transport_sockets.quic
      typed_config:
        "@type": type.googleapis.com/envoy.extensions.transport_sockets.quic.v3.QuicUpstreamTransport
        upstream_tls_context:
          common_tls_context:
            tls_certificates:
            - certificate_chain:
                filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem"
              private_key:
                filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem"
            validation_context:
              trusted_ca:
                filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem"
              match_typed_subject_alt_names:
              - matcher:
                  exact: localhost
                san_type: URI
              - matcher:
                  exact: 127.0.0.1
                san_type: IP_ADDRESS
  )EOF",
                                                       Network::Address::IpVersion::v4);
  auto cluster1 = makeCluster(yaml);
  ASSERT_TRUE(cluster1->info()->idleTimeout().has_value());
  EXPECT_EQ(std::chrono::hours(1), cluster1->info()->idleTimeout().value());

  const std::string explicit_http3 = R"EOF(
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config:
          http3_protocol_options:
            quic_protocol_options:
              max_concurrent_streams: 2
        common_http_protocol_options:
          idle_timeout: 1s
  )EOF";

  const std::string downstream_http3 = R"EOF(
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        use_downstream_protocol_config:
          http3_protocol_options: {}
        common_http_protocol_options:
          idle_timeout: 1s
  )EOF";

  auto explicit_h3 = makeCluster(yaml + explicit_http3);
  EXPECT_EQ(Http::Protocol::Http3,
            explicit_h3->info()->upstreamHttpProtocol({Http::Protocol::Http10})[0]);
  EXPECT_EQ(
      explicit_h3->info()->http3Options().quic_protocol_options().max_concurrent_streams().value(),
      2);

  auto downstream_h3 = makeCluster(yaml + downstream_http3);
  EXPECT_EQ(Http::Protocol::Http3,
            downstream_h3->info()->upstreamHttpProtocol({Http::Protocol::Http3})[0]);
  EXPECT_FALSE(
      downstream_h3->info()->http3Options().quic_protocol_options().has_max_concurrent_streams());
}


static MagickBooleanType DrawStrokePolygon(Image *image,
  const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
  ExceptionInfo *exception)
{
  DrawInfo
    *clone_info;

  MagickBooleanType
    closed_path;

  MagickStatusType
    status;

  PrimitiveInfo
    *stroke_polygon;

  register const PrimitiveInfo
    *p,
    *q;

  /*
    Draw stroked polygon.
  */
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(DrawEvent,GetMagickModule(),
      "    begin draw-stroke-polygon");
  clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
  clone_info->fill=draw_info->stroke;
  if (clone_info->fill_pattern != (Image *) NULL)
    clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
  if (clone_info->stroke_pattern != (Image *) NULL)
    clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
      MagickTrue,exception);
  clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
  clone_info->stroke_width=0.0;
  clone_info->fill_rule=NonZeroRule;
  status=MagickTrue;
  for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
  {
    stroke_polygon=TraceStrokePolygon(draw_info,p);
    status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
    if (status == 0)
      break;
    stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
    q=p+p->coordinates-1;
    closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
      MagickTrue : MagickFalse;
    if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
      {
        DrawRoundLinecap(image,draw_info,p,exception);
        DrawRoundLinecap(image,draw_info,q,exception);
      }
  }
  clone_info=DestroyDrawInfo(clone_info);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(DrawEvent,GetMagickModule(),
      "    end draw-stroke-polygon");
  return(status != 0 ? MagickTrue : MagickFalse);
}


static inline ulong encode_twos_comp(long n, int prec)
{
	ulong result;
	assert(prec >= 2);
	jas_eprintf("warning: support for signed data is untested\n");
	// NOTE: Is this correct?
	if (n < 0) {
		result = -n;
		result = (result ^ 0xffffffffUL) + 1;
		result &= (1 << prec) - 1;
	} else {
		result = n;
	}
	return result;
}


b});return g},writeCssText:function(a,c){var d,g=[];for(d in a)g.push(d+":"+a[d]);c&&g.sort();return g.join("; ")},objectCompare:function(a,c,d){var g;if(!a&&!c)return true;if(!a||!c)return false;for(g in a)if(a[g]!=c[g])return false;if(!d)for(g in c)if(a[g]!=c[g])return false;return true},objectKeys:function(a){var c=[],d;for(d in a)c.push(d);return c},convertArrayToObject:function(a,c){var d={};arguments.length==1&&(c=true);for(var g=0,e=a.length;g<e;++g)d[a[g]]=c;return d},fixDomain:function(){for(var a;;)try{a=


parse_cmd_address(exarg_T *eap, char **errormsg, int silent)
{
    int		address_count = 1;
    linenr_T	lnum;

    // Repeat for all ',' or ';' separated addresses.
    for (;;)
    {
	eap->line1 = eap->line2;
	eap->line2 = default_address(eap);
	eap->cmd = skipwhite(eap->cmd);
	lnum = get_address(eap, &eap->cmd, eap->addr_type, eap->skip, silent,
					eap->addr_count == 0, address_count++);
	if (eap->cmd == NULL)	// error detected
	    return FAIL;
	if (lnum == MAXLNUM)
	{
	    if (*eap->cmd == '%')   // '%' - all lines
	    {
		++eap->cmd;
		switch (eap->addr_type)
		{
		    case ADDR_LINES:
		    case ADDR_OTHER:
			eap->line1 = 1;
			eap->line2 = curbuf->b_ml.ml_line_count;
			break;
		    case ADDR_LOADED_BUFFERS:
			{
			    buf_T	*buf = firstbuf;

			    while (buf->b_next != NULL
						  && buf->b_ml.ml_mfp == NULL)
				buf = buf->b_next;
			    eap->line1 = buf->b_fnum;
			    buf = lastbuf;
			    while (buf->b_prev != NULL
						  && buf->b_ml.ml_mfp == NULL)
				buf = buf->b_prev;
			    eap->line2 = buf->b_fnum;
			    break;
			}
		    case ADDR_BUFFERS:
			eap->line1 = firstbuf->b_fnum;
			eap->line2 = lastbuf->b_fnum;
			break;
		    case ADDR_WINDOWS:
		    case ADDR_TABS:
			if (IS_USER_CMDIDX(eap->cmdidx))
			{
			    eap->line1 = 1;
			    eap->line2 = eap->addr_type == ADDR_WINDOWS
						  ? LAST_WIN_NR : LAST_TAB_NR;
			}
			else
			{
			    // there is no Vim command which uses '%' and
			    // ADDR_WINDOWS or ADDR_TABS
			    *errormsg = _(e_invalid_range);
			    return FAIL;
			}
			break;
		    case ADDR_TABS_RELATIVE:
		    case ADDR_UNSIGNED:
		    case ADDR_QUICKFIX:
			*errormsg = _(e_invalid_range);
			return FAIL;
		    case ADDR_ARGUMENTS:
			if (ARGCOUNT == 0)
			    eap->line1 = eap->line2 = 0;
			else
			{
			    eap->line1 = 1;
			    eap->line2 = ARGCOUNT;
			}
			break;
		    case ADDR_QUICKFIX_VALID:
#ifdef FEAT_QUICKFIX
			eap->line1 = 1;
			eap->line2 = qf_get_valid_size(eap);
			if (eap->line2 == 0)
			    eap->line2 = 1;
#endif
			break;
		    case ADDR_NONE:
			// Will give an error later if a range is found.
			break;
		}
		++eap->addr_count;
	    }
	    else if (*eap->cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
	    {
		pos_T	    *fp;

		// '*' - visual area
		if (eap->addr_type != ADDR_LINES)
		{
		    *errormsg = _(e_invalid_range);
		    return FAIL;
		}

		++eap->cmd;
		if (!eap->skip)
		{
		    fp = getmark('<', FALSE);
		    if (check_mark(fp) == FAIL)
			return FAIL;
		    eap->line1 = fp->lnum;
		    fp = getmark('>', FALSE);
		    if (check_mark(fp) == FAIL)
			return FAIL;
		    eap->line2 = fp->lnum;
		    ++eap->addr_count;
		}
	    }
	}
	else
	    eap->line2 = lnum;
	eap->addr_count++;

	if (*eap->cmd == ';')
	{
	    if (!eap->skip)
	    {
		curwin->w_cursor.lnum = eap->line2;
		// Don't leave the cursor on an illegal line or column, but do
		// accept zero as address, so 0;/PATTERN/ works correctly.
		if (eap->line2 > 0)
		    check_cursor();
	    }
	}
	else if (*eap->cmd != ',')
	    break;
	++eap->cmd;
    }

    // One address given: set start and end lines.
    if (eap->addr_count == 1)
    {
	eap->line1 = eap->line2;
	// ... but only implicit: really no address given
	if (lnum == MAXLNUM)
	    eap->addr_count = 0;
    }
    return OK;
}


    def rpn(self, irc, msg, args):
        """<rpn math expression>

        Returns the value of an RPN expression.
        """
        stack = []
        for arg in args:
            try:
                x = complex(arg)
                if x == abs(x):
                    x = abs(x)
                stack.append(x)
            except ValueError: # Not a float.
                if arg in self._mathSafeEnv:
                    f = self._mathSafeEnv[arg]
                    if callable(f):
                        called = False
                        arguments = []
                        while not called and stack:
                            arguments.append(stack.pop())
                            try:
                                stack.append(f(*arguments))
                                called = True
                            except TypeError:
                                pass
                        if not called:
                            irc.error(_('Not enough arguments for %s') % arg)
                            return
                    else:
                        stack.append(f)
                elif arg in self._rpnEnv:
                    self._rpnEnv[arg](stack)
                else:
                    arg2 = stack.pop()
                    arg1 = stack.pop()
                    s = '%s%s%s' % (arg1, arg, arg2)
                    try:
                        stack.append(eval(s, self._mathSafeEnv, self._mathSafeEnv))
                    except SyntaxError:
                        irc.error(format(_('%q is not a defined function.'),
                                         arg))
                        return
        if len(stack) == 1:
            irc.reply(str(self._complexToString(complex(stack[0]))))
        else:
            s = ', '.join(map(self._complexToString, list(map(complex, stack))))
            irc.reply(_('Stack: [%s]') % s)


			filter = function(file) {

				if (file && file.hash && file.name && file.mime) {
					if (file.mime == 'application/x-empty') {
						file.mime = 'text/plain';
					}

					if (! file.phash || file.mime === 'directory') {
						// set options, tmbUrls for each volume
						if (file.volumeid) {
							// from v2.1.14
							if (file.options) {
								// set volOptions
								self.volOptions[file.volumeid] = file.options;

								// set immediate properties
								$.each(self.optionProperties, function(i, k) {
									if (file.options[k]) {
										file[k] = file.options[k];
									}
								});
							} else {
								// for compat <= v2.1.13
								if (file.disabled) {
									self.volOptions[file.volumeid].disabled = file.disabled;
								}
								if (file.tmbUrl) {
									self.volOptions[file.volumeid].tmbUrl = file.tmbUrl;
								}
							}
							if (! file.phash) {
								self.roots[file.volumeid] = file.hash;
							}

							if (prevId !== file.volumeid) {
								prevId = file.volumeid;
								i18nFolderName = self.option('i18nFolderName', file.volumeid);
							}
						}

						// volume root i18n name
						if (! file.i18 && ! file.phash) {
							name = 'volume_' + file.name,
							i18 = self.i18n(false, name);

							if (name !== i18) {
								file.i18 = i18;
							}
						}

						// i18nFolderName
						if (i18nFolderName && ! file.i18) {
							name = 'folder_' + file.name,
							i18 = self.i18n(false, name);

							if (name !== i18) {
								file.i18 = i18;
							}
						}
					}

					return file;
				}
				return null;
			},


    it "should not update an arbitary model (sanitizes input)" do
      where_stub = double
      where_stub.should_receive(:update_all).with(:state => "Expanded")
      Comment.should_receive(:where).and_return(where_stub)
      xhr :get, :timeline, :id => "1,2,3,4+", :state => "Expanded"
    end


callback    : function() { input.select().focus(); }


    public function __construct($attr, $css)
    {
        $this->attr = $attr;
        $this->css = $css;
    }


		const walkHtmlTokens = (tokens:any[]) => {
			if (!tokens || !tokens.length) return;

			for (const token of tokens) {
				if (!['html_block', 'html_inline'].includes(token.type)) {
					walkHtmlTokens(token.children);
					continue;
				}

				const cacheKey = md5(escape(token.content));
				let sanitizedContent = context.cache.get(cacheKey);

				if (!sanitizedContent) {
					sanitizedContent = htmlUtils.sanitizeHtml(token.content);
				}

				token.content = sanitizedContent;

				context.cache.put(cacheKey, sanitizedContent, 1000 * 60 * 60);
				walkHtmlTokens(token.children);
			}
		};


        public RecurlyList<Transaction> GetTransactions(TransactionList.TransactionState state = TransactionList.TransactionState.All,
            TransactionList.TransactionType type = TransactionList.TransactionType.All)
        {
            return new TransactionList(UrlPrefix + Uri.EscapeUriString(AccountCode) + "/transactions/"
                 + Build.QueryStringWith(state != TransactionList.TransactionState.All ? "state=" + state.ToString().EnumNameToTransportCase() : "")
                   .AndWith(type != TransactionList.TransactionType.All ? "type=" + type.ToString().EnumNameToTransportCase() : ""));
        }


    public static function hasChildren($i) {
        global $sections;

        if (($i + 1) >= count($sections)) return false;
        return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;
    }


static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
				    u64 nr,
				    struct perf_sample_data *data,
				    struct pt_regs *regs)
{
	struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
	struct perf_event *event;
	struct hlist_node *node;
	struct hlist_head *head;

	rcu_read_lock();
	head = find_swevent_head_rcu(swhash, type, event_id);
	if (!head)
		goto end;

	hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
		if (perf_swevent_match(event, type, event_id, data, regs))
			perf_swevent_event(event, nr, data, regs);
	}
end:
	rcu_read_unlock();
}


	fatalError:function(error) {
		console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
	    throw error;
	}


  def users
    Log.add_info(request, params.inspect)

    con = []

    unless params[:keyword].blank?
      key_array = params[:keyword].split(nil)
      key_array.each do |key|
        con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization], key)
      end
    end

    @group_id = nil
    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].blank?
      @group_id = params[:group_id]
    end
    SqlHelper.validate_token([@group_id])

    unless @group_id.nil?
      con << SqlHelper.get_sql_like([:groups], "|#{@group_id}|")
    end

    include_research = false

    filter_status = params[:filter_status]

    unless filter_status.blank?
      SqlHelper.validate_token([filter_status])
      case filter_status
        when Research::U_STATUS_IN_ACTON.to_s, Research::U_STATUS_COMMITTED.to_s
          con << "((Research.user_id=User.id) and (Research.status=#{filter_status}))"
          include_research = true
        when (-1).to_s
          researches = Research.where(nil).to_a
          except_users = []
          unless researches.nil?
            researches.each do |research|
              except_users << research.user_id
            end
          end
          unless except_users.empty?
            con << '(User.id not in (' + except_users.join(',') + '))'
          end
        else
          ;
      end
    end


Mat_VarReadNextInfo4(mat_t *mat)
{
    int       M,O,data_type,class_type;
    mat_int32_t tmp;
    long      nBytes;
    size_t    readresult;
    matvar_t *matvar = NULL;
    union {
        mat_uint32_t u;
        mat_uint8_t  c[4];
    } endian;

    if ( mat == NULL || mat->fp == NULL )
        return NULL;
    else if ( NULL == (matvar = Mat_VarCalloc()) )
        return NULL;

    readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
    if ( 1 != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    }

    endian.u = 0x01020304;

    /* See if MOPT may need byteswapping */
    if ( tmp < 0 || tmp > 4052 ) {
        if ( Mat_int32Swap(&tmp) > 4052 ) {
            Mat_VarFree(matvar);
            return NULL;
        }
    }

    M = (int)floor(tmp / 1000.0);
    switch ( M ) {
        case 0:
            /* IEEE little endian */
            mat->byteswap = endian.c[0] != 4;
            break;
        case 1:
            /* IEEE big endian */
            mat->byteswap = endian.c[0] != 1;
            break;
        default:
            /* VAX, Cray, or bogus */
            Mat_VarFree(matvar);
            return NULL;
    }

    tmp -= M*1000;
    O = (int)floor(tmp / 100.0);
    /* O must be zero */
    if ( 0 != O ) {
        Mat_VarFree(matvar);
        return NULL;
    }

    tmp -= O*100;
    data_type = (int)floor(tmp / 10.0);
    /* Convert the V4 data type */
    switch ( data_type ) {
        case 0:
            matvar->data_type = MAT_T_DOUBLE;
            break;
        case 1:
            matvar->data_type = MAT_T_SINGLE;
            break;
        case 2:
            matvar->data_type = MAT_T_INT32;
            break;
        case 3:
            matvar->data_type = MAT_T_INT16;
            break;
        case 4:
            matvar->data_type = MAT_T_UINT16;
            break;
        case 5:
            matvar->data_type = MAT_T_UINT8;
            break;
        default:
            Mat_VarFree(matvar);
            return NULL;
    }

    tmp -= data_type*10;
    class_type = (int)floor(tmp / 1.0);
    switch ( class_type ) {
        case 0:
            matvar->class_type = MAT_C_DOUBLE;
            break;
        case 1:
            matvar->class_type = MAT_C_CHAR;
            break;
        case 2:
            matvar->class_type = MAT_C_SPARSE;
            break;
        default:
            Mat_VarFree(matvar);
            return NULL;
    }

    matvar->rank = 2;
    matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
    if ( NULL == matvar->dims ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
    if ( mat->byteswap )
        Mat_int32Swap(&tmp);
    matvar->dims[0] = tmp;
    if ( 1 != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
    if ( mat->byteswap )
        Mat_int32Swap(&tmp);
    matvar->dims[1] = tmp;
    if ( 1 != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    }

    readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
    if ( 1 != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
    if ( 1 != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    if ( mat->byteswap )
        Mat_int32Swap(&tmp);
    /* Check that the length of the variable name is at least 1 */
    if ( tmp < 1 ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    matvar->name = (char*)malloc(tmp);
    if ( NULL == matvar->name ) {
        Mat_VarFree(matvar);
        return NULL;
    }
    readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
    if ( tmp != readresult ) {
        Mat_VarFree(matvar);
        return NULL;
    } else {
        matvar->name[tmp - 1] = '\0';
    }

    matvar->internal->datapos = ftell((FILE*)mat->fp);
    if ( matvar->internal->datapos == -1L ) {
        Mat_VarFree(matvar);
        Mat_Critical("Couldn't determine file position");
        return NULL;
    }
    {
        int err;
        size_t tmp2 = Mat_SizeOf(matvar->data_type);
        if ( matvar->isComplex )
            tmp2 *= 2;
        err = SafeMulDims(matvar, &tmp2);
        if ( err ) {
            Mat_VarFree(matvar);
            Mat_Critical("Integer multiplication overflow");
            return NULL;
        }

        nBytes = (long)tmp2;
    }
    (void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);

    return matvar;
}


    public function testFromParts($input)
    {
        $uri = Uri::fromParts(parse_url($input));

        $this->assertSame($input, (string) $uri);
    }


    public function event()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();
        $values['project_id'] = $project['id'];

        if (empty($values['action_name'])) {
            return $this->create();
        }

        return $this->response->html($this->template->render('action_creation/event', array(
            'values' => $values,
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


    def run_query(self, query, user):
        path = ""
        ua = ""
        args = {}
        try:
            args = yaml.safe_load(query)
            path = args['url']
            args.pop('url', None)
            ua = args['user-agent']
            args.pop('user-agent', None)

            if is_private_address(path) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:
                raise Exception("Can't query private addresses.")
        except:
            pass

        try:
            response = requests.get(url=path, headers={"User-agent": ua})
            workbook = pd.read_excel(response.content, **args)

            df = workbook.copy()
            data = {'columns': [], 'rows': []}
            conversions = [
                {'pandas_type': np.integer, 'redash_type': 'integer',},
                {'pandas_type': np.inexact, 'redash_type': 'float',},
                {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},
                {'pandas_type': np.bool_, 'redash_type': 'boolean'},
                {'pandas_type': np.object, 'redash_type': 'string'}
            ]
            labels = []
            for dtype, label in zip(df.dtypes, df.columns):
                for conversion in conversions:
                    if issubclass(dtype.type, conversion['pandas_type']):
                        data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})
                        labels.append(label)
                        func = conversion.get('to_redash')
                        if func:
                            df[label] = df[label].apply(func)
                        break
            data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')

            json_data = json_dumps(data)
            error = None
        except KeyboardInterrupt:
            error = "Query cancelled by user."
            json_data = None
        except Exception as e:
            error = "Error reading {0}. {1}".format(path, str(e))
            json_data = None

        return json_data, error


        public async Task<ConnectorResult> ExtractAsync(FullPath fullPath, bool newFolder)
        {
            var response = new AddResponseModel();

            if (fullPath.IsDirectory || fullPath.File.Extension.ToLower() != ".zip")
            {
                throw new NotSupportedException("Only .zip files are currently supported.");
            }

            string rootPath = fullPath.File.Directory.FullName;

            if (newFolder)
            {
                rootPath = Path.Combine(rootPath, Path.GetFileNameWithoutExtension(fullPath.File.Name));
                var rootDir = new FileSystemDirectory(rootPath);
                if (!await rootDir.ExistsAsync)
                {
                    await rootDir.CreateAsync();
                }
                response.Added.Add(await BaseModel.CreateAsync(rootDir, fullPath.RootVolume));
            }

            using (var archive = ZipFile.OpenRead(fullPath.File.FullName))
            {
                string separator = Path.DirectorySeparatorChar.ToString();
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    try
                    {
                        //Replce zip entry path separator by system path separator
                        string file = Path.Combine(rootPath, entry.FullName)
                             .Replace("/", separator).Replace("\\", separator);

                        string destPath = Path.GetFullPath(file);
                        if (!destPath.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new NotSupportedException($"Entry '{entry.FullName}' is outside of the destination directory.");
                        }

                        if (file.EndsWith(separator)) //directory
                        {
                            var dir = new FileSystemDirectory(file);

                            if (!await dir.ExistsAsync)
                            {
                                await dir.CreateAsync();
                            }
                            if (!newFolder)
                            {
                                response.Added.Add(await BaseModel.CreateAsync(dir, fullPath.RootVolume));
                            }
                        }
                        else
                        {
                            entry.ExtractToFile(file, true);
                            if (!newFolder)
                            {
                                response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(file), fullPath.RootVolume));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("{0} - {1}", entry.FullName, ex.Message);
                    }
                }
            }

            return new ConnectorResult(response);
        }


static void voutf(struct GlobalConfig *config,
                  const char *prefix,
                  const char *fmt,
                  va_list ap)
{
  size_t width = (79 - strlen(prefix));
  if(!config->mute) {
    size_t len;
    char *ptr;
    char *print_buffer;

    print_buffer = curlx_mvaprintf(fmt, ap);
    if(!print_buffer)
      return;
    len = strlen(print_buffer);

    ptr = print_buffer;
    while(len > 0) {
      fputs(prefix, config->errors);

      if(len > width) {
        size_t cut = width-1;

        while(!ISSPACE(ptr[cut]) && cut) {
          cut--;
        }
        if(0 == cut)
          /* not a single cutting position was found, just cut it at the
             max text width then! */
          cut = width-1;

        (void)fwrite(ptr, cut + 1, 1, config->errors);
        fputs("\n", config->errors);
        ptr += cut + 1; /* skip the space too */
        len -= cut;
      }
      else {
        fputs(ptr, config->errors);
        len = 0;
      }
    }
    curl_free(print_buffer);
  }
}


    public function testProfilePages () {
        $this->visitPages ($this->getPages ('^profile'));
    }


    function send_to_iframes(key, data) {
        // propagate events to iframes
        iframes.forEach(function(iframe) {
            var payload = {
              name: uniq_prefix,
              key: key,
              data: data
            };
            iframe.window.postMessage(JSON.stringify(payload), "*");
        });
    }


setTemplates: function() {
            var iconHTML = '';
            if (this.options.suggestionIcon !== '') {
                iconHTML = '';
            }

            // suggestions
            if (this.options.fields.length) {
                this.suggestionTpl = this.sandbox.util.template('' +
                    '<div class="' + this.options.suggestionClass + '" data-id="<%= context[\'id \']%>">' +
                    '
' +
                    '
' +
                    '           <% _.each(fields, function(field, idx) { %>' +
                    '           <div class="suggestion-column" style="width: <%= field.width %>;"><%= context[field.id] %>
' +
                    '           <% }) %>' +
                    '
' +
                    '
' +
                    '
');
            } else {
                this.suggestionTpl = this.sandbox.util.template('' +
                    '<div class="' + this.options.suggestionClass + '" data-id="<%= context[\'id \']%>">' +
                    '
' +
                            iconHTML +
                    '
<%= context[this.options.valueKey] %>
' +
                    '
' +
                    '
');
            }

            if (!!this.options.footerContent) {
                this.footerTpl = this.sandbox.util.template(
                    '
' +
                        this.options.footerContent +
                    '
'
                );
            }
        },


    private function getError( $code, $id = null, $data = null )
    {
        return array(
            'jsonrpc' => '2.0',
            'id'      => $id,
            'error'   => array(
                'code'    => $code,
                'message' => isset($this->errorMessages[$code]) ? $this->errorMessages[$code] : $this->errorMessages[self::InternalError],
                'data'    => $data,
            ),
        );
    }


  public XMLInputFactory newXMLInputFactory() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    setPropertyQuietly(factory, XMLInputFactory.SUPPORT_DTD, false);
    setPropertyQuietly(factory, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    return factory;
  }


    public function getMethod()
    {
        return 'listPaths';
    }


    public function getDisplayName ($plural=true, $ofModule=true) {
        return Yii::t('users', '{user}', array(
            '{user}' => Modules::displayName($plural, 'Users'),
        ));
    }


    public function isDeprecated()
    {
        return $this->deprecated;
    }


function PHPMailerAutoload($classname)
{
    //Can't use __DIR__ as it's only in PHP 5.3+
    $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
    if (is_readable($filename)) {
        require $filename;
    }
}


			$iloc = expUnserialize($container->internal);
			if ($db->selectObject('sectionref',"module='".$iloc->mod."' AND source='".$iloc->src."'") == null) {
			// There is no sectionref for this container.  Populate sectionref
                if ($container->external != "N;") {
                    $newSecRef = new stdClass();
                    $newSecRef->module   = $iloc->mod;
                    $newSecRef->source   = $iloc->src;
                    $newSecRef->internal = '';
                    $newSecRef->refcount = 1;
//                    $newSecRef->is_original = 1;
					$eloc = expUnserialize($container->external);
//					$section = $db->selectObject('sectionref',"module='containermodule' AND source='".$eloc->src."'");
                    $section = $db->selectObject('sectionref',"module='container' AND source='".$eloc->src."'");
					if (!empty($section)) {
						$newSecRef->section = $section->id;
						$db->insertObject($newSecRef,"sectionref");
						$missing_sectionrefs[] = gt("Missing sectionref for container replaced").": ".$iloc->mod." - ".$iloc->src." - PageID #".$section->id;
					} else {
                        $db->delete('container','id="'.$container->id.'"');
                        $missing_sectionrefs[] = gt("Cant' find the container page for container").": ".$iloc->mod." - ".$iloc->src.' - '.gt('deleted');
					}
				}
			}
		}
        assign_to_template(array(
            'missing_sectionrefs'=>$missing_sectionrefs,
        ));
	}


	static public function addCategory($_category = null, $_admin = 1, $_order = 1) {

		if ($_category != null
			&& $_category != ''
		) {
			if ($_order < 1) {
				$_order = 1;
			}

			$ins_stmt = Database::prepare("
				INSERT INTO `" . TABLE_PANEL_TICKET_CATS . "` SET
					`name` = :name,
					`adminid` = :adminid,
					`logicalorder` = :lo"
			);
			$ins_data = array(
				'name' => $_category,
				'adminid' => $_admin,
				'lo' => $_order
			);
			Database::pexecute($ins_stmt, $ins_data);
			return true;
		}
		return false;
	}


public static function getMenu($menuid, $class='', $bsnav=false){
        $menus = self::getMenuRaw($menuid);
        $n = Db::$num_rows;
        if($n > 0){
            $menu = "
";
            foreach ($menus as $m) {
                # code...
                if($m->parent == ''){
                    $parent = self::getParent($m->id, $menuid);
                    $n = Db::$num_rows;
                    if($n > 0 && $bsnav) {
                        $class = "class=\"dropdown\"";
                        $aclass = "dropdown-toggle\" data-toggle=\"dropdown";
                    }else{
                        $class ="";
                        $aclass = "";
                    }
                    $type = $m->type;
                    $menu .= "
";
                    $menu .= "value)."' class=\"{$m->class} {$aclass}\">".$m->name."";
                    $parent = $m->id;
                    //echo $parent;

                    if($n > 0){
                        $class = "dropdown-menu";
                        $menu .= "
";
                            foreach ($menus as $m2) {
                                if($m2->parent == $m->id){
                                    $parent = self::getParent($m2->id, $menuid);
                                    $n = Db::$num_rows;
                                    if($n > 0 && $bsnav) {
                                        $class = "class=\"dropdown\"";
                                        $aclass = "dropdown-toggle\" data-toggle=\"dropdown";
                                    }else{
                                        $class ="";
                                        $aclass = "";
                                    }
                                    $type = $m2->type;
                                    $menu .= "
";
                                    $menu .= "value)."' class=\"{$m2->class} {$aclass}\">".$m2->name."";

                                        if($n > 0){
                                            $class = "dropdown-menu";
                                            $menu .= "
";
                                            foreach ($menus as $m3) {
                                                if($m3->parent == $m2->id){
                                                    $parent = self::getParent($m3->id, $menuid);
                                                    $n = Db::$num_rows;
                                                    if($n > 0 && $bsnav) {
                                                        $class = "class=\"dropdown\"";
                                                        $aclass = "dropdown-toggle\" data-toggle=\"dropdown";
                                                    }else{
                                                        $class ="";
                                                        $aclass = "";
                                                    }
                                                    $type = $m3->type;
                                                    $menu .= "
";
                                                    $menu .= "
";
                                                    $menu .= "value)."' class=\"{$m3->class} {$aclass}\">".$m3->name."";

                                                        if($n > 0){
                                                            $class = "dropdown-menu";
                                                            $menu .= "
";
                                                            foreach ($menus as $m4) {
                                                                if($m4->parent == $m3->id){
                                                                    $parent = self::getParent($m4->id, $menuid);
                                                                    $n = Db::$num_rows;
                                                                    if($n > 0 && $bsnav) {
                                                                        $class = "class=\"dropdown\"";
                                                                        $aclass = "dropdown-toggle\" data-toggle=\"dropdown";
                                                                    }else{
                                                                        $class ="";
                                                                        $aclass = "";
                                                                    }
                                                                    $type = $m4->type;
                                                                    $menu .= "
";
                                                                    $menu .= "value)."' class=\"{$m4->class} {$aclass}\">".$m4->name."";
                                                                    $menu .= "
";
                                                                }
                                                            }
                                                            $menu .= "
";
                                                        }
                                                    $menu .= "
";
                                                }
                                            }
                                            $menu .= "
";
                                        }
                                    $menu .= "
";
                                }
                            }
                            $menu .= "
";
                    }

                    $menu .= "
";
                }

            }
            $menu .= "
";
        }else{
            $menu = "";
        }

        return $menu;
    }


replSpinner = function(msg) { dialog.find('.'+spclass).parent().text(msg); },


    function import() {
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname);
        $modules = new expPaginator(array(
            'records' => $pullable_modules,
            'controller' => $this->loc->mod,
            'action' => $this->params['action'],
            'order'   => isset($this->params['order']) ? $this->params['order'] : 'section',
            'dir'     => isset($this->params['dir']) ? $this->params['dir'] : '',
            'page'    => (isset($this->params['page']) ? $this->params['page'] : 1),
            'columns' => array(
                gt('Title') => 'title',
                gt('Page')  => 'section'
            ),
        ));

        assign_to_template(array(
            'modules' => $modules,
        ));
    }


bool SampleInterleavedLSScan::ParseMCU(void)
{
#if ACCUSOFT_CODE
  int lines             = m_ulRemaining[0]; // total number of MCU lines processed.
  UBYTE preshift        = m_ucLowBit + FractionalColorBitsOf();
  struct Line *line[4];
  UBYTE cx;

  //
  // If a DNL marker is present, the number of remaining lines is zero. Fix it.
  if (m_pFrame->HeightOf() == 0) {
    assert(lines == 0);
    lines = 8;
  }
  //
  // A "MCU" in respect to the code organization is eight lines.
  if (lines > 8) {
    lines = 8;
  }

  if (lines == 0)
    return false;

  if (m_pFrame->HeightOf() > 0)
    m_ulRemaining[0] -= lines;
  assert(m_ucCount < 4);

  //
  // Fill the line pointers.
  for(cx = 0;cx < m_ucCount;cx++) {
    line[cx] = CurrentLine(cx);
  }

  // Loop over lines and columns
  do {
    LONG length = m_ulWidth[0];
    LONG *lp[4];

    // Get the line pointers and initialize the internal backup lines.
    for(cx = 0;cx < m_ucCount;cx++) {
      lp[cx] = line[cx]->m_pData;
      StartLine(cx);
    }

    if (BeginReadMCU(m_Stream.ByteStreamOf())) {
      // No error handling strategy. No RST in scans. Bummer!
      do {
        LONG a[4],b[4],c[4],d[4]; // neighbouring values.
        LONG d1[4],d2[4],d3[4];   // local gradients.
        bool isrun = true;

        for(cx = 0;cx < m_ucCount;cx++) {
          GetContext(cx,a[cx],b[cx],c[cx],d[cx]);

          d1[cx]  = d[cx] - b[cx];    // compute local gradients
          d2[cx]  = b[cx] - c[cx];
          d3[cx]  = c[cx] - a[cx];

          //
          // Run mode only if the run condition is met for all components
          if (isrun && !isRunMode(d1[cx],d2[cx],d3[cx]))
            isrun = false;
        }

        if (isrun) {
          LONG run = DecodeRun(length,m_lRunIndex[0]);
          //
          // Now fill the data.
          while(run) {
            // Update so that the next process gets the correct value.
            // There is one sample per component.
            for(cx = 0;cx < m_ucCount;cx++) {
              UpdateContext(cx,a[cx]);
              // And insert the value into the target line as well.
              *lp[cx]++ = a[cx] << preshift;
            }
            run--,length--;
            // As long as there are pixels on the line.
          }
          //
          // More data on the line? I.e. the run did not cover the full m_lJ samples?
          // Now decode the run interruption sample. The rtype is here always zero.
          if (length) {
            bool negative; // the sign variable
            LONG errval;   // the prediction error
            LONG merr;     // the mapped error (symbol)
            LONG rx;       // the reconstructed value
            UBYTE k;       // golomb parameter
            //
            // Decode the interrupting pixels.
            for(cx = 0;cx < m_ucCount;cx++) {
              // Get the neighbourhood.
              GetContext(cx,a[cx],b[cx],c[cx],d[cx]);
              // The prediction mode is always false, but the sign information
              // is required.
              negative = a[cx] > b[cx];
              // Get the golomb parameter for run interruption coding.
              k       = GolombParameter(false);
              // Golomb-decode the error symbol. It is always using the common
              // run index.
              merr    = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);
              // Inverse the error mapping procedure.
              errval  = InverseErrorMapping(merr,ErrorMappingOffset(false,merr != 0,k));
              // Compute the reconstructed value.
              rx      = Reconstruct(negative,b[cx],errval);
              // Update so that the next process gets the correct value.
              UpdateContext(cx,rx);
              // Fill in the value into the line
              *lp[cx]++ = rx << preshift;
              // Update the variables of the run mode.
              UpdateState(false,errval);
            }
            // Update the run index now. This is not part of
            // EncodeRun because the non-reduced run-index is
            // required for the golomb coder length limit.
            if (m_lRunIndex[0] > 0)
              m_lRunIndex[0]--;
          } else break; // end of line.
        } else {
          UWORD ctxt;
          bool  negative; // the sign variable.
          LONG  px;       // the predicted variable.
          LONG  rx;       // the reconstructed value.
          LONG  errval;   // the error value.
          LONG  merr;     // the mapped error value.
          UBYTE k;        // the Golomb parameter.
          //
          for(cx = 0;cx < m_ucCount;cx++) {
            // Quantize the gradients.
            d1[cx]  = QuantizedGradient(d1[cx]);
            d2[cx]  = QuantizedGradient(d2[cx]);
            d3[cx]  = QuantizedGradient(d3[cx]);
            // Compute the context.
            ctxt    = Context(negative,d1[cx],d2[cx],d3[cx]);
            // Compute the predicted value.
            px      = Predict(a[cx],b[cx],c[cx]);
            // Correct the prediction.
            px      = CorrectPrediction(ctxt,negative,px);
            // Compute the golomb parameter k from the context.
            k       = GolombParameter(ctxt);
            // Decode the error symbol.
            merr    = GolombDecode(k,m_lLimit);
            // Inverse the error symbol into an error value.
            errval  = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));
            // Update the variables.
            UpdateState(ctxt,errval);
            // Compute the reconstructed value.
            rx      = Reconstruct(negative,px,errval);
            // Update so that the next process gets the correct value.
            UpdateContext(cx,rx);
            // And insert the value into the target line as well.
            *lp[cx]++ = rx << preshift;
          }
        }
      } while(--length);
    } // No error handling here.
    //
    // Advance the line pointers.
    for(cx = 0;cx < m_ucCount;cx++) {
      EndLine(cx);
      line[cx] = line[cx]->m_pNext;
    }
    //
  } while(--lines);
  //
  // If this is the last line, gobble up all the
  // bits from bitstuffing the last byte may have left.
  // As SkipStuffing is idempotent, we can also do that
  // all the time.
  m_Stream.SkipStuffing();
#endif
  return false;
}


static int put_chars(u32 vtermno, const char *buf, int count)
{
	struct port *port;
	struct scatterlist sg[1];

	if (unlikely(early_put_chars))
		return early_put_chars(vtermno, buf, count);

	port = find_port_by_vtermno(vtermno);
	if (!port)
		return -EPIPE;

	sg_init_one(sg, buf, count);
	return __send_to_port(port, sg, 1, count, (void *)buf, false);
}


public function testParagraphInBlockquote()
    {
        $this->assertResult(
'
Par1

Par2
',
'

Par1

Par2

'
        );
    }


MOBI_RET mobi_search_links_kf7(MOBIResult *result, const unsigned char *data_start, const unsigned char *data_end) {
    if (!result) {
        debug_print("Result structure is null%s", "\n");
        return MOBI_PARAM_ERR;
    }
    result->start = result->end = NULL;
    *(result->value) = '\0';
    if (!data_start || !data_end) {
        debug_print("Data is null%s", "\n");
        return MOBI_PARAM_ERR;
    }
    const char *needle1 = "filepos=";
    const char *needle2 = "recindex=";
    const size_t needle1_length = strlen(needle1);
    const size_t needle2_length = strlen(needle2);
    const size_t needle_length = max(needle1_length,needle2_length);
    if (data_start + needle_length > data_end) {
        return MOBI_SUCCESS;
    }
    unsigned char *data = (unsigned char *) data_start;
    const unsigned char tag_open = '<';
    const unsigned char tag_close = '>';
    unsigned char last_border = tag_open;
    while (data <= data_end) {
        if (*data == tag_open || *data == tag_close) {
            last_border = *data;
        }
        if (data + needle_length <= data_end &&
            (memcmp(data, needle1, needle1_length) == 0 ||
             memcmp(data, needle2, needle2_length) == 0)) {
                /* found match */
                if (last_border != tag_open) {
                    /* opening char not found, not an attribute */
                    data += needle_length;
                    continue;
                }
                /* go to attribute  beginning */
                while (data >= data_start && !isspace(*data) && *data != tag_open) {
                    data--;
                }
                result->start = ++data;
                /* now go forward */
                int i = 0;
                while (data <= data_end && !isspace(*data) && *data != tag_close && i < MOBI_ATTRVALUE_MAXSIZE) {
                    result->value[i++] = (char) *data++;
                }
                /* self closing tag '/>' */
                if (*(data - 1) == '/' && *data == '>') {
                    --data; --i;
                }
                result->end = data;
                result->value[i] = '\0';
                return MOBI_SUCCESS;
            }
        data++;
    }
    return MOBI_SUCCESS;
}


		"": function(checkSet, part, isXML){
			var doneName = "done" + (done++), checkFn = dirCheck;

			if ( !part.match(/\W/) ) {
				var nodeCheck = part = isXML ? part : part.toUpperCase();
				checkFn = dirNodeCheck;
			}

			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
		},


        public void DoUpdate(AgentUpdateInfo agentUpdateInfo) {
            _agentUpdateInfo = agentUpdateInfo;
            _logger.Log(String.Format("Received from Agent the following data:\r\nURL:{0}\r\nCHECKSUM:{1}, will resume in a minute", _agentUpdateInfo.url, _agentUpdateInfo.signature));

            new Timer(TimerElapsed,null,60000,0);
        }


function format(s, style, color, background, _class, data_text, text) {
                function pre_process_link(data) {
                    var result;
                    if (data.match(email_re)) {
                        result = '<a href="mailto:' + data + '"';
                    } else {
                        // only http and ftp links (prevent javascript)
                        // unless user force it with anyLinks option
                        if (!valid_href(data)) {
                            data = '';
                        }
                        result = '<a target="_blank"';
                        if (data) {
                            result += ' href="' + data + '"';
                        }
                        result += ' rel="' + rel_attr().join(' ') + '"';
                    }
                    return result;
                }
                function pre_process_image(data) {
                    var result = '<img';
                    if (valid_src(data)) {
                        result += ' src="' + data + '"';
                        if (text) {
                            result += ' alt="' + text + '"';
                        }
                    }
                    return result;
                }
                var attrs;
                if (data_text.match(/;/)) {
                    try {
                        var splitted = data_text.split(';');
                        var str = splitted.slice(1).join(';')
                            .replace(/ /g, ' ')
                            .replace(/</g, '<')
                            .replace(/>/g, '>');
                        if (str.match(/^\s*\{[^}]*\}\s*$/)) {
                            attrs = JSON.parse(str);
                            data_text = splitted[0];
                        }
                    } catch (e) {
                    }
                }
                if (text === '' && !style.match(/@/)) {
                    return ''; //' ';
                }
                text = safe(text);
                text = text.replace(/\\\]/g, ']');
                if (settings.escape) {
                    // inside formatting we need to unescape escaped slashes
                    // but this escape is not needed when echo - don't know why
                    text = text.replace(/\\\\/g, '\\');
                }
                var style_str = '';
                if (style.indexOf('b') !== -1) {
                    style_str += 'font-weight:bold;';
                }
                var text_decoration = [];
                if (style.indexOf('u') !== -1) {
                    text_decoration.push('underline');
                }
                if (style.indexOf('s') !== -1) {
                    text_decoration.push('line-through');
                }
                if (style.indexOf('o') !== -1) {
                    text_decoration.push('overline');
                }
                if (text_decoration.length) {
                    style_str += 'text-decoration:' +
                        text_decoration.join(' ') + ';';
                }
                if (style.indexOf('i') !== -1) {
                    style_str += 'font-style:italic;';
                }
                if ($.terminal.valid_color(color)) {
                    style_str += [
                        'color:' + color,
                        '--color:' + color,
                        '--original-color:' + color
                    ].join(';') + ';';
                    if (style.indexOf('!') !== -1) {
                        style_str += '--link-color:' + color + ';';
                    }
                    if (style.indexOf('g') !== -1) {
                        style_str += 'text-shadow:0 0 5px ' + color + ';';
                    }
                }
                if ($.terminal.valid_color(background)) {
                    style_str += [
                        'background-color:' + background,
                        '--background:' + background
                    ].join(';') + ';';
                }
                var data = clean_data(data_text, text);
                var extra = extra_css(text, settings);
                if (extra) {
                    text = wide_characters(text, settings);
                    style_str += extra;
                }
                var result;
                if (style.indexOf('!') !== -1) {
                    result = pre_process_link(data);
                } else if (style.indexOf('@') !== -1) {
                    result = pre_process_image(data);
                } else {
                    result = '<span';
                }
                if (attrs && attrs.style) {
                    // merge style attr and colors #617
                    attrs.style = style_str + attrs.style;
                    style_str = '';
                }
                result += add_attrs(attrs);
                if (style_str !== '') {
                    result += ' style="' + style_str + '"';
                }
                if (_class !== '') {
                    result += ' class="' + _class + '"';
                }
                // links and image need data-text attribute cmd click behavior
                // formatter can return links.
                if (style.indexOf('!') !== -1) {
                    result += ' data-text>' + text + '';
                } else if (style.indexOf('@') !== -1) {
                    result += ' data-text/>';
                } else {
                    result += ' data-text="' + data.replace(/"/g, '"') + '">' +
                        '' + text + '';
                }
                return result;
            }


    protected function addBinary($left, $right) {
        $len    = max(strlen($left), strlen($right));
        $left   = str_pad($left, $len, chr(0), STR_PAD_LEFT);
        $right  = str_pad($right, $len, chr(0), STR_PAD_LEFT);
        $result = '';
        $carry  = 0;
        for ($i = 0; $i < $len; $i++) {
            $sum     = ord($left[$len - $i - 1])
                 + ord($right[$len - $i - 1])
                 + $carry;
            $result .= chr($sum % 256);
            $carry   = $sum >> 8;
        }
        while ($carry) {
            $result .= chr($carry % 256);
            $carry >>= 8;
        }
        return strrev($result);
    }