  inlineTokens(src, tokens = [], inLink = false, inRawBlock = false) {
    let token, lastToken;

    // String with links masked to avoid interference with em and strong
    let maskedSrc = src;
    let match;
    let keepPrevChar, prevChar;

    // Mask out reflinks
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    // Mask out other blocks
    while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }

    while (src) {
      if (!keepPrevChar) {
        prevChar = '';
      }
      keepPrevChar = false;
      // escape
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }

      // tag
      if (token = this.tokenizer.tag(src, inLink, inRawBlock)) {
        src = src.substring(token.raw.length);
        inLink = token.inLink;
        inRawBlock = token.inRawBlock;
        const lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === 'text' && lastToken.type === 'text') {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }

      // link
      if (token = this.tokenizer.link(src)) {
        src = src.substring(token.raw.length);
        if (token.type === 'link') {
          token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
        }
        tokens.push(token);
        continue;
      }

      // reflink, nolink
      if (token = this.tokenizer.reflink(src, this.tokens.links)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens[tokens.length - 1];
        if (token.type === 'link') {
          token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
          tokens.push(token);
        } else if (lastToken && token.type === 'text' && lastToken.type === 'text') {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }

      // strong
      if (token = this.tokenizer.strong(src, maskedSrc, prevChar)) {
        src = src.substring(token.raw.length);
        token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
        tokens.push(token);
        continue;
      }

      // em
      if (token = this.tokenizer.em(src, maskedSrc, prevChar)) {
        src = src.substring(token.raw.length);
        token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
        tokens.push(token);
        continue;
      }

      // code
      if (token = this.tokenizer.codespan(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }

      // br
      if (token = this.tokenizer.br(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }

      // del (gfm)
      if (token = this.tokenizer.del(src)) {
        src = src.substring(token.raw.length);
        token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
        tokens.push(token);
        continue;
      }

      // autolink
      if (token = this.tokenizer.autolink(src, mangle)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }

      // url (gfm)
      if (!inLink && (token = this.tokenizer.url(src, mangle))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }

      // text
      if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) {
        src = src.substring(token.raw.length);
        prevChar = token.raw.slice(-1);
        keepPrevChar = true;
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === 'text') {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }

      if (src) {
        const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }

    return tokens;
  }


        it 'inserts the specified line after the line matching the "after" expression' do
          provider.create
          expect(File.read(@tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz")
        end


        it "executes the operation on a slave node" do
          session.should_receive(:socket_for).with(:read).
            and_return(socket)
          socket.should_receive(:execute).with(operation)

          session.execute(operation)
        end


function NyanCat(runner) {
  Base.call(this, runner);
  var self = this
    , stats = this.stats
    , width = Base.window.width * .75 | 0
    , rainbowColors = this.rainbowColors = self.generateColors()
    , colorIndex = this.colorIndex = 0
    , numerOfLines = this.numberOfLines = 4
    , trajectories = this.trajectories = [[], [], [], []]
    , nyanCatWidth = this.nyanCatWidth = 11
    , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
    , scoreboardWidth = this.scoreboardWidth = 5
    , tick = this.tick = 0
    , n = 0;

  runner.on('start', function(){
    Base.cursor.hide();
    self.draw();
  });

  runner.on('pending', function(test){
    self.draw();
  });

  runner.on('pass', function(test){
    self.draw();
  });

  runner.on('fail', function(test, err){
    self.draw();
  });

  runner.on('end', function(){
    Base.cursor.show();
    for (var i = 0; i < self.numberOfLines; i++) write('\n');
    self.epilogue();
  });
}


  function onReady() {
    if (this === client) {
      assert(!clientReady,
             msg('Received multiple ready events for client'));
      clientReady = true;
      this.sftp(mustCall((err, sftp) => {
        assert(!err, msg(`Unexpected client sftp start error: ${err}`));
        clientSFTP = sftp;
        sftp.on('end', mustCall(() => {
          this.end();
        }));
        onSFTP.call(this);
      }));
    } else {
      assert(!serverReady,
             msg('Received multiple ready events for server'));
      serverReady = true;
      this.once('session', mustCall((accept, reject) => {
        accept().once('sftp', mustCall((accept, reject) => {
          const sftp = accept();
          serverSFTP = sftp;
          sftp.on('end', mustCall(() => {
            this.end();
          }));
          onSFTP.call(this);
        }));
      }));
    }
  }


                        $r = $this->info[$validator_name]->validate(
                            $bits[$i],
                            $config,
                            $context
                        );
                        if ($r !== false) {
                            $final .= $r . ' ';
                            $caught[$validator_name] = true;
                            break;
                        }
                    }
                    // all three caught, continue on
                    if (count($caught) >= 3) {
                        $stage = 1;
                    }
                    if ($r !== false) {
                        break;
                    }
                case 1: // attempting to catch font-size and perhaps line-height
                    $found_slash = false;
                    if (strpos($bits[$i], '/') !== false) {
                        list($font_size, $line_height) =
                            explode('/', $bits[$i]);
                        if ($line_height === '') {
                            // ooh, there's a space after the slash!
                            $line_height = false;
                            $found_slash = true;
                        }
                    } else {
                        $font_size = $bits[$i];
                        $line_height = false;
                    }
                    $r = $this->info['font-size']->validate(
                        $font_size,
                        $config,
                        $context
                    );
                    if ($r !== false) {
                        $final .= $r;
                        // attempt to catch line-height
                        if ($line_height === false) {
                            // we need to scroll forward
                            for ($j = $i + 1; $j < $size; $j++) {
                                if ($bits[$j] === '') {
                                    continue;
                                }
                                if ($bits[$j] === '/') {
                                    if ($found_slash) {
                                        return false;
                                    } else {
                                        $found_slash = true;
                                        continue;
                                    }
                                }
                                $line_height = $bits[$j];
                                break;
                            }
                        } else {
                            // slash already found
                            $found_slash = true;
                            $j = $i;
                        }
                        if ($found_slash) {
                            $i = $j;
                            $r = $this->info['line-height']->validate(
                                $line_height,
                                $config,
                                $context
                            );
                            if ($r !== false) {
                                $final .= '/' . $r;
                            }
                        }
                        $final .= ' ';
                        $stage = 2;
                        break;
                    }
                    return false;
                case 2: // attempting to catch font-family
                    $font_family =
                        implode(' ', array_slice($bits, $i, $size - $i));
                    $r = $this->info['font-family']->validate(
                        $font_family,
                        $config,
                        $context
                    );
                    if ($r !== false) {
                        $final .= $r . ' ';
                        // processing completed successfully
                        return rtrim($final);
                    }
                    return false;
            }
        }
        return false;
    }


func (svc *Service) ListUsers(ctx context.Context, opt fleet.UserListOptions) ([]*fleet.User, error) {
	if err := svc.authz.Authorize(ctx, &fleet.User{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	return svc.ds.ListUsers(ctx, opt)
}


rdpsnd_process_training(STREAM in)
{
	uint16 tick;
	uint16 packsize;
	STREAM out;
	struct stream packet = *in;

	if (!s_check_rem(in, 4))
	{
		rdp_protocol_error("rdpsnd_process_training(), consume of training data from stream would overrun", &packet);
	}

	in_uint16_le(in, tick);
	in_uint16_le(in, packsize);

	logger(Sound, Debug, "rdpsnd_process_training(), tick=0x%04x", (unsigned) tick);

	out = rdpsnd_init_packet(SNDC_TRAINING, 4);
	out_uint16_le(out, tick);
	out_uint16_le(out, packsize);
	s_mark_end(out);
	rdpsnd_send(out);
}


	switch (type) {
#ifdef ELFCORE
	case ET_CORE:
		flags |= FLAGS_IS_CORE;
		if (dophn_core(ms, clazz, swap, fd,
		    (off_t)elf_getu(swap, elfhdr.e_phoff),
		    elf_getu16(swap, elfhdr.e_phnum),
		    (size_t)elf_getu16(swap, elfhdr.e_phentsize),
		    fsize, &flags) == -1)
			return -1;
		break;
#endif
	case ET_EXEC:
	case ET_DYN:
		if (dophn_exec(ms, clazz, swap, fd,
		    (off_t)elf_getu(swap, elfhdr.e_phoff),
		    elf_getu16(swap, elfhdr.e_phnum),
		    (size_t)elf_getu16(swap, elfhdr.e_phentsize),
		    fsize, &flags, elf_getu16(swap, elfhdr.e_shnum))
		    == -1)
			return -1;
		/*FALLTHROUGH*/
	case ET_REL:
		if (doshn(ms, clazz, swap, fd,
		    (off_t)elf_getu(swap, elfhdr.e_shoff),
		    elf_getu16(swap, elfhdr.e_shnum),
		    (size_t)elf_getu16(swap, elfhdr.e_shentsize),
		    fsize, &flags, elf_getu16(swap, elfhdr.e_machine),
		    (int)elf_getu16(swap, elfhdr.e_shstrndx)) == -1)
			return -1;
		break;

	default:
		break;
	}


  constructor(initial) {
    this.mode = (initial && initial.mode);
    this.uid = (initial && initial.uid);
    this.gid = (initial && initial.gid);
    this.size = (initial && initial.size);
    this.atime = (initial && initial.atime);
    this.mtime = (initial && initial.mtime);
    this.extended = (initial && initial.extended);
  }


    public function has($path)
    {
        $location = $this->applyPathPrefix($path);

        return file_exists($location);
    }


	public function editspeed() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        assign_to_template(array(
            'calculator'=>$calc
        ));

    }


    def connect
      return true if connection

      Timeout::timeout 0.5 do
        @connection = TCPSocket.new(host, port)
      end
    rescue Errno::ECONNREFUSED, Timeout::Error
      return false
    end


  public MultiMap set(String name, Iterable<String> values) {
    HttpUtils.validateHeader(name, values);
    headers.set(toLowerCase(name), values);
    return this;
  }


    public ResetPasswordRequestResponse requestResetPassword(UserReference userReference) throws ResetPasswordException
    {
        this.checkUserReference(userReference);

        UserProperties userProperties = this.userPropertiesResolver.resolve(userReference);
        InternetAddress email = userProperties.getEmail();

        if (email == null) {
            String exceptionMessage =
                this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noEmail");
            throw new ResetPasswordException(exceptionMessage);
        }

        DocumentUserReference documentUserReference = (DocumentUserReference) userReference;
        DocumentReference reference = documentUserReference.getReference();
        XWikiContext context = this.contextProvider.get();

        try {
            XWikiDocument userDocument = context.getWiki().getDocument(reference, context);

            if (userDocument.getXObject(LDAP_CLASS_REFERENCE) != null) {
                String exceptionMessage =
                    this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.ldapUser",
                        userReference.toString());
                throw new ResetPasswordException(exceptionMessage);
            }

            BaseObject xObject = userDocument.getXObject(RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, context);
            String verificationCode = context.getWiki().generateRandomString(30);
            xObject.set(VERIFICATION_PROPERTY, verificationCode, context);

            String saveComment =
                this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment");
            context.getWiki().saveDocument(userDocument, saveComment, true, context);

            return new DefaultResetPasswordRequestResponse(userReference, email, verificationCode);
        } catch (XWikiException e) {
            throw new ResetPasswordException("Error when reading user document to perform reset password request.", e);
        }
    }


static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d)
{
	u8 obuf[] = { 0x51 };
	u8 ibuf[] = { 0 };

	if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0)
		err("command 0x51 transfer failed.");

	d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config,
					&d->dev->i2c_adap);

	if (d->fe_adap[0].fe == NULL)
		return -EIO;

	if (dvb_attach(ts2020_attach, d->fe_adap[0].fe,
				&dw2104_ts2020_config,
				&d->dev->i2c_adap)) {
		info("Attached RS2000/TS2020!");
		return 0;
	}

	info("Failed to attach RS2000/TS2020!");
	return -EIO;
}


        public OldECIESwithCipher(BlockCipher baseCipher)
        {
            super(new OldIESEngine(new ECDHBasicAgreement(),
                new KDF2BytesGenerator(new SHA1Digest()),
                new HMac(new SHA1Digest()),
                new PaddedBufferedBlockCipher(baseCipher)));
        }


static void error_handler(int err, void *arg)
{
	error("Engine just broken: %m.\n", err);
}


def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]:
    """Split a server name into host/port parts.

    No validation is done on the host part. The port part is validated to be
    a valid port number.

    Args:
        server_name: server name to parse

    Returns:
        host/port parts.

    Raises:
        ValueError if the server name could not be parsed.
    """
    try:
        if server_name[-1] == "]":
            # ipv6 literal, hopefully
            return server_name, None

        host_port = server_name.rsplit(":", 1)
        host = host_port[0]
        port = host_port[1] if host_port[1:] else None

        if port:
            port_num = int(port)

            # exclude things like '08090' or ' 8090'
            if port != str(port_num) or not (1 <= port_num < 65536):
                raise ValueError("Invalid port")

        return host, port
    except Exception:
        raise ValueError("Invalid server name '%s'" % server_name)


    public void testValidationKeyStorage() throws Exception
    {
        XWikiContext context = this.oldcore.getXWikiContext();
        context.setLanguage("en");

        // Prepare the request
        XWikiRequest request = mock(XWikiRequest.class);
        when(request.getParameter("xwikiname")).thenReturn("TestUser");
        when(request.getParameter("validkey")).thenReturn("plaintextkey");
        context.setRequest(request);

        // Prepare the user profile
        XWikiDocument testUser =
            new XWikiDocument(new DocumentReference(this.oldcore.getXWikiContext().getWikiId(), "XWiki", "TestUser"));
        BaseObject userObject = (BaseObject) this.xwiki.getUserClass(context).newObject(context);

        // Check with a correct plaintext key
        BaseProperty validationKey = new StringProperty();
        validationKey.setValue("plaintextkey");
        userObject.safeput("validkey", validationKey);
        testUser.addObject("XWiki.XWikiUsers", userObject);

        this.xwiki.saveDocument(testUser, context);

        assertEquals(0, this.xwiki.validateUser(false, this.oldcore.getXWikiContext()));
        XWikiDocument reloadedDocument = this.xwiki.getDocument(testUser, context);
        assertEquals("", reloadedDocument.getObject("XWiki.XWikiUsers").getStringValue("validkey"));

        // Check with an incorrect plaintext key
        validationKey.setValue("wrong key");
        this.xwiki.saveDocument(testUser, context);

        assertEquals(-1, this.xwiki.validateUser(false, this.oldcore.getXWikiContext()));

        // Check with a correct hashed key
        validationKey = ((PropertyClass) this.xwiki.getUserClass(context).get("validkey")).fromString("plaintextkey");
        assertTrue(validationKey.getValue().toString().startsWith("hash:"));
        userObject.safeput("validkey", validationKey);
        this.xwiki.saveDocument(testUser, context);

        assertEquals(0, this.xwiki.validateUser(false, this.oldcore.getXWikiContext()));

        // Check with an incorrect hashed key
        validationKey = ((PropertyClass) this.xwiki.getUserClass(context).get("validkey")).fromString("wrong key");
        assertTrue(validationKey.getValue().toString().startsWith("hash:"));
        userObject.safeput("validkey", validationKey);
        this.xwiki.saveDocument(testUser, context);

        assertEquals(-1, this.xwiki.validateUser(false, this.oldcore.getXWikiContext()));
    }


static void br_multicast_del_pg(struct net_bridge *br,
				struct net_bridge_port_group *pg)
{
	struct net_bridge_mdb_htable *mdb;
	struct net_bridge_mdb_entry *mp;
	struct net_bridge_port_group *p;
	struct net_bridge_port_group __rcu **pp;

	mdb = mlock_dereference(br->mdb, br);

	mp = br_mdb_ip_get(mdb, &pg->addr);
	if (WARN_ON(!mp))
		return;

	for (pp = &mp->ports;
	     (p = mlock_dereference(*pp, br)) != NULL;
	     pp = &p->next) {
		if (p != pg)
			continue;

		rcu_assign_pointer(*pp, p->next);
		hlist_del_init(&p->mglist);
		del_timer(&p->timer);
		call_rcu_bh(&p->rcu, br_multicast_free_pg);

		if (!mp->ports && !mp->mglist &&
		    netif_running(br->dev))
			mod_timer(&mp->timer, jiffies);

		return;
	}

	WARN_ON(1);
}


    public function getSize($path)
    {
        return $this->getMetadata($path);
    }


    def concat_wrapper():
      y = gen_array_ops.concat_v2(
          values=[[1, 2, 3], [4, 5, 6]], axis=0xb500005b)
      return y


    public function save()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }


static void nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
	struct nlm_rqst	*req = data;
	u32 status = ntohl(req->a_res.status);

	if (RPC_ASSASSINATED(task))
		goto die;

	if (task->tk_status < 0) {
		dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
		switch (task->tk_status) {
		case -EACCES:
		case -EIO:
			goto die;
		default:
			goto retry_rebind;
		}
	}
	if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
		rpc_delay(task, NLMCLNT_GRACE_WAIT);
		goto retry_unlock;
	}
	if (status != NLM_LCK_GRANTED)
		printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
	return;
 retry_rebind:
	nlm_rebind_host(req->a_host);
 retry_unlock:
	rpc_restart_call(task);
}


void ntlm_print_negotiate_flags(UINT32 flags)
{
	int i;
	const char* str;
	WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags);

	for (i = 31; i >= 0; i--)
	{
		if ((flags >> i) & 1)
		{
			str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
			WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
		}
	}
}


    public function testSupports()
    {
        $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());

        $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }


				$fieldPickListValues[$value] = \App\Language::translate($value, $this->getModuleName(),false,false);
			}
			// Protection against deleting a value that does not exist on the list
			if ('picklist' === $fieldDataType) {
				$fieldValue = $this->get('fieldvalue');
				if (!empty($fieldValue) && !isset($fieldPickListValues[$fieldValue])) {
					$fieldPickListValues[$fieldValue] = \App\Language::translate($fieldValue, $this->getModuleName(),false,false);
					$this->set('isEditableReadOnly', true);
				}
			}
		} elseif (method_exists($this->getUITypeModel(), 'getPicklistValues')) {


static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
	struct packet_rollover *rollover = NULL;
	struct packet_sock *po = pkt_sk(sk);
	struct packet_fanout *f, *match;
	u8 type = type_flags & 0xff;
	u8 flags = type_flags >> 8;
	int err;

	switch (type) {
	case PACKET_FANOUT_ROLLOVER:
		if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
			return -EINVAL;
	case PACKET_FANOUT_HASH:
	case PACKET_FANOUT_LB:
	case PACKET_FANOUT_CPU:
	case PACKET_FANOUT_RND:
	case PACKET_FANOUT_QM:
	case PACKET_FANOUT_CBPF:
	case PACKET_FANOUT_EBPF:
		break;
	default:
		return -EINVAL;
	}

	mutex_lock(&fanout_mutex);

	err = -EINVAL;
	if (!po->running)
		goto out;

	err = -EALREADY;
	if (po->fanout)
		goto out;

	if (type == PACKET_FANOUT_ROLLOVER ||
	    (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
		err = -ENOMEM;
		rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
		if (!rollover)
			goto out;
		atomic_long_set(&rollover->num, 0);
		atomic_long_set(&rollover->num_huge, 0);
		atomic_long_set(&rollover->num_failed, 0);
		po->rollover = rollover;
	}

	match = NULL;
	list_for_each_entry(f, &fanout_list, list) {
		if (f->id == id &&
		    read_pnet(&f->net) == sock_net(sk)) {
			match = f;
			break;
		}
	}
	err = -EINVAL;
	if (match && match->flags != flags)
		goto out;
	if (!match) {
		err = -ENOMEM;
		match = kzalloc(sizeof(*match), GFP_KERNEL);
		if (!match)
			goto out;
		write_pnet(&match->net, sock_net(sk));
		match->id = id;
		match->type = type;
		match->flags = flags;
		INIT_LIST_HEAD(&match->list);
		spin_lock_init(&match->lock);
		atomic_set(&match->sk_ref, 0);
		fanout_init_data(match);
		match->prot_hook.type = po->prot_hook.type;
		match->prot_hook.dev = po->prot_hook.dev;
		match->prot_hook.func = packet_rcv_fanout;
		match->prot_hook.af_packet_priv = match;
		match->prot_hook.id_match = match_fanout_group;
		dev_add_pack(&match->prot_hook);
		list_add(&match->list, &fanout_list);
	}
	err = -EINVAL;
	if (match->type == type &&
	    match->prot_hook.type == po->prot_hook.type &&
	    match->prot_hook.dev == po->prot_hook.dev) {
		err = -ENOSPC;
		if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
			__dev_remove_pack(&po->prot_hook);
			po->fanout = match;
			atomic_inc(&match->sk_ref);
			__fanout_link(sk, po);
			err = 0;
		}
	}
out:
	if (err && rollover) {
		kfree(rollover);
		po->rollover = NULL;
	}
	mutex_unlock(&fanout_mutex);
	return err;
}


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

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

        $action = $this->actionManager->getAction($values['action_name']);
        $action_params = $action->getActionRequiredParameters();

        if (empty($action_params)) {
            $this->doCreation($project, $values + array('params' => array()));
        }

        $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
        unset($projects_list[$project['id']]);

        $this->response->html($this->template->render('action_creation/params', array(
            'values' => $values,
            'action_params' => $action_params,
            'columns_list' => $this->columnModel->getList($project['id']),
            'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
            'projects_list' => $projects_list,
            'colors_list' => $this->colorModel->getList(),
            'categories_list' => $this->categoryModel->getList($project['id']),
            'links_list' => $this->linkModel->getList(0, false),
            'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'swimlane_list' => $this->swimlaneModel->getList($project['id']),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


function wrapmessage(title, message, count, ago, persistent) {
    let html = '

' + title + '

' + message + '
';

    let additional = '';

    if (count > 1) additional += client.translate('Event repeated %1 times.', count) + ' ';
    let units = client.translate('minutes');
    if (ago > 60) {
      ago = ago / 60;
      ago = Math.round((ago + Number.EPSILON) * 10) / 10;
      units = client.translate('hours');
    }
    if (ago == 0) { ago = client.translate('less than 1'); }
    if (!persistent && ago) additional += client.translate('Last recorded %1 %2 ago.', ago, units);

    if (additional) html += '
' + additional + '
'
    return html;
  }


translate_hex_string(char *s, char *saved_orphan)
{
  int c1 = *saved_orphan;
  char *start = s;
  char *t = s;
  for (; *s; s++) {
    if (isspace((unsigned char) *s))
      continue;
    if (c1) {
      *t++ = (hexval(c1) << 4) + hexval(*s);
      c1 = 0;
    } else
      c1 = *s;
  }
  *saved_orphan = c1;
  return t - start;
}


	public function upload($_files , $file_key , $uid , $item_id = 0  , $page_id = 0  ){
		$uploadFile = $_files[$file_key] ;

		if( !$this->isAllowedFilename($_files[$file_key]['name']) ){
			return false;
		}

		$oss_open = D("Options")->get("oss_open" ) ;
		if ($oss_open) {
				$url = $this->uploadOss($uploadFile);
				if ($url) {
						$sign = md5($url.time().rand()) ;
						$insert = array(
						"sign" => $sign,
						"uid" => $uid,
						"item_id" => $item_id,
						"page_id" => $page_id,
						"display_name" => $uploadFile['name'],
						"file_type" => $uploadFile['type'],
						"file_size" => $uploadFile['size'],
						"real_url" => $url,
						"addtime" => time(),
						);
						$file_id = D("UploadFile")->add($insert);
						$insert = array(
							"file_id" => $file_id,
							"item_id" => $item_id,
							"page_id" => $page_id,
							"addtime" => time(),
							);
						$ret = D("FilePage")->add($insert);
						$url = server_url("api/attachment/visitFile",array("sign" => $sign));
					  return $url ;
				}
		}else{
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize  = 1003145728 ;// 设置附件上传大小
			$upload->rootPath = './../Public/Uploads/';// 设置附件上传目录
			$upload->savePath = '';// 设置附件上传子目录
			$info = $upload->uploadOne($uploadFile) ;
			if(!$info) {// 上传错误提示错误信息
				var_dump($upload->getError());
				return;
			}else{// 上传成功 获取上传文件信息
				$url = site_url().'/Public/Uploads/'.$info['savepath'].$info['savename'] ;
				$sign = md5($url.time().rand()) ;
				$insert = array(
					"sign" => $sign,
					"uid" => $uid,
					"item_id" => $item_id,
					"page_id" => $page_id,
					"display_name" => $uploadFile['name'],
					"file_type" => $uploadFile['type'],
					"file_size" => $uploadFile['size'],
					"real_url" => $url,
					"addtime" => time(),
					);
					$file_id = D("UploadFile")->add($insert);
					$insert = array(
						"file_id" => $file_id,
						"item_id" => $item_id,
						"page_id" => $page_id,
						"addtime" => time(),
						);
					$ret = D("FilePage")->add($insert);
				$url = server_url("api/attachment/visitFile",array("sign" => $sign));
				return $url ;
			}
		}
		return false;
	}


func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
	sess := x.Limit(20, (page-1)*20)

	if rid > 0 {
		sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
	} else {
		sess.Where("is_closed=?", isClosed)
	}

	if uid > 0 {
		sess.And("assignee_id=?", uid)
	} else if pid > 0 {
		sess.And("poster_id=?", pid)
	}

	if mid > 0 {
		sess.And("milestone_id=?", mid)
	}

	if len(labelIds) > 0 {
		for _, label := range strings.Split(labelIds, ",") {
			sess.And("label_ids like '%$" + label + "|%'")
		}
	}

	switch sortType {
	case "oldest":
		sess.Asc("created")
	case "recentupdate":
		sess.Desc("updated")
	case "leastupdate":
		sess.Asc("updated")
	case "mostcomment":
		sess.Desc("num_comments")
	case "leastcomment":
		sess.Asc("num_comments")
	case "priority":
		sess.Desc("priority")
	default:
		sess.Desc("created")
	}

	var issues []Issue
	err := sess.Find(&issues)
	return issues, err
}


static pyc_object *get_set_object(RBuffer *buffer) {
	bool error = false;
	ut32 n = get_ut32 (buffer, &error);
	if (n > ST32_MAX) {
		eprintf ("bad marshal data (set size out of range)\n");
		return NULL;
	}
	if (error) {
		return NULL;
	}
	pyc_object *ret = get_array_object_generic (buffer, n);
	if (ret) {
		ret->type = TYPE_SET;
	}
	return ret;
}


		public function cloneRepository($url, $directory = NULL, array $params = NULL)
		{
			if ($directory !== NULL && is_dir("$directory/.git")) {
				throw new GitException("Repo already exists in $directory.");
			}

			$cwd = $this->runner->getCwd();

			if ($directory === NULL) {
				$directory = Helpers::extractRepositoryNameFromUrl($url);
				$directory = "$cwd/$directory";

			} elseif(!Helpers::isAbsolute($directory)) {
				$directory = "$cwd/$directory";
			}

			if ($params === NULL) {
				$params = '-q';
			}

			try {
				$this->run($cwd, [
					'clone',
					$params,
					'--end-of-options',
					$url,
					$directory
				]);

			} catch (GitException $e) {
				$stderr = '';
				$result = $e->getRunnerResult();

				if ($result !== NULL && $result->hasErrorOutput()) {
					$stderr = implode(PHP_EOL, $result->getErrorOutput());
				}

				throw new GitException("Git clone failed (directory $directory)." . ($stderr !== '' ? ("\n$stderr") : ''));
			}


    private function add($s1, $s2, $scale)
    {
        if ($this->bcmath) {
            return bcadd($s1, $s2, $scale);
        } else {
            return $this->scale((float)$s1 + (float)$s2, $scale);
        }
    }


__u32 secure_ipv6_id(const __be32 daddr[4])
{
	const struct keydata *keyptr;
	__u32 hash[4];

	keyptr = get_keyptr();

	hash[0] = (__force __u32)daddr[0];
	hash[1] = (__force __u32)daddr[1];
	hash[2] = (__force __u32)daddr[2];
	hash[3] = (__force __u32)daddr[3];

	return half_md4_transform(hash, keyptr->secret);
}


    public void parseURL(ApplContext ac, URL url, String title,
                         String kind, String media,
                         int origin) {
        boolean doneref = false;
        URL ref = ac.getReferrer();
        setWarningLevel(ac.getWarningLevel());
        if (Util.onDebug) {
            System.err.println("StyleSheet.parseURL(" + url + ", "
                    + title + ", "
                    + kind + ", " + media + ", "
                    + origin + ")");
        }
        if (kind != null) {
            kind = kind.trim().toLowerCase();
            if (!kind.equals("stylesheet") && !kind.equals("alternate stylesheet")) {
                return;
            }
        }
        try {
            ac.setOrigin(origin);
//	    if (cssFouffa == null) {
            cssFouffa = new CssFouffa(ac, url);
            cssFouffa.addListener(this);
//	    } else {
//		cssFouffa.ReInit(ac, url);
//	    }

            //	    cssFouffa.setResponse(res);

            // removed plh 2001-03-08
            // cssFouffa.setOrigin(origin);
            //	    cssFouffa.setDefaultMedium(defaultmedium);
            //	    cssFouffa.doConfig();
            if (media == null) {
                if (ac.getCssVersion() != CssVersion.CSS1) {
                    if (ac.getMedium() == null) {
                        media = "all";
                    } else {
                        media = ac.getMedium();
                    }
                }
            }
            AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion());
            try {
                if (media != null) {
                    addMedias(m, media, ac);
                }
                cssFouffa.setAtRule(m);
            } catch (org.w3c.css.util.InvalidParamException e) {
                Errors er = new Errors();
                er.addError(new org.w3c.css.parser.CssError(url.toString(),
                        -1, e));
                notifyErrors(er);
                return;
            }
            ac.setReferrer(url);
            doneref = true;
            cssFouffa.parseStyle();
        } catch (Exception e) {
            Errors er = new Errors();
            er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()),
                    -1, e));
            notifyErrors(er);
        } finally {
            if (doneref) {
                ac.setReferrer(ref);
            }
        }
    }


    objectKeys(data).forEach((key) => {
      obj.add(deserializer(data[key], baseType) as T);
    });


static int MqttClient_WaitType(MqttClient *client, void *packet_obj,
    byte wait_type, word16 wait_packet_id, int timeout_ms)
{
    int rc;
    word16 packet_id;
    MqttPacketType packet_type;
#ifdef WOLFMQTT_MULTITHREAD
    MqttPendResp *pendResp;
    int readLocked;
#endif
    MqttMsgStat* mms_stat;
    int waitMatchFound;

    if (client == NULL || packet_obj == NULL) {
        return MQTT_CODE_ERROR_BAD_ARG;
    }

    /* all packet type structures must have MqttMsgStat at top */
    mms_stat = (MqttMsgStat*)packet_obj;

wait_again:

    /* initialize variables */
    packet_id = 0;
    packet_type = MQTT_PACKET_TYPE_RESERVED;
#ifdef WOLFMQTT_MULTITHREAD
    pendResp = NULL;
    readLocked = 0;
#endif
    waitMatchFound = 0;

#ifdef WOLFMQTT_DEBUG_CLIENT
    PRINTF("MqttClient_WaitType: Type %s (%d), ID %d",
        MqttPacket_TypeDesc((MqttPacketType)wait_type),
            wait_type, wait_packet_id);
#endif

    switch ((int)*mms_stat)
    {
        case MQTT_MSG_BEGIN:
        {
        #ifdef WOLFMQTT_MULTITHREAD
            /* Lock recv socket mutex */
            rc = wm_SemLock(&client->lockRecv);
            if (rc != 0) {
                PRINTF("MqttClient_WaitType: recv lock error!");
                return rc;
            }
            readLocked = 1;
        #endif

            /* reset the packet state */
            client->packet.stat = MQTT_PK_BEGIN;
        }
        FALL_THROUGH;

    #ifdef WOLFMQTT_V5
        case MQTT_MSG_AUTH:
    #endif
        case MQTT_MSG_WAIT:
        {
        #ifdef WOLFMQTT_MULTITHREAD
            /* Check to see if packet type and id have already completed */
            pendResp = NULL;
            rc = wm_SemLock(&client->lockClient);
            if (rc == 0) {
                if (MqttClient_RespList_Find(client, (MqttPacketType)wait_type,
                    wait_packet_id, &pendResp)) {
                    if (pendResp->packetDone) {
                        /* pending response is already done, so return */
                        rc = pendResp->packet_ret;
                    #ifdef WOLFMQTT_DEBUG_CLIENT
                        PRINTF("PendResp already Done %p: Rc %d", pendResp, rc);
                    #endif
                        MqttClient_RespList_Remove(client, pendResp);
                        wm_SemUnlock(&client->lockClient);
                        wm_SemUnlock(&client->lockRecv);
                        return rc;
                    }
                }
                wm_SemUnlock(&client->lockClient);
            }
            else {
                break; /* error */
            }
        #endif /* WOLFMQTT_MULTITHREAD */

            *mms_stat = MQTT_MSG_WAIT;

            /* Wait for packet */
            rc = MqttPacket_Read(client, client->rx_buf, client->rx_buf_len,
                    timeout_ms);
            /* handle failure */
            if (rc <= 0) {
                break;
            }

            /* capture length read */
            client->packet.buf_len = rc;

            /* Decode Packet - get type and id */
            rc = MqttClient_DecodePacket(client, client->rx_buf,
                client->packet.buf_len, NULL, &packet_type, NULL, &packet_id);
            if (rc < 0) {
                break;
            }

        #ifdef WOLFMQTT_DEBUG_CLIENT
            PRINTF("Read Packet: Len %d, Type %d, ID %d",
                client->packet.buf_len, packet_type, packet_id);
        #endif

            *mms_stat = MQTT_MSG_READ;
        }
        FALL_THROUGH;

        case MQTT_MSG_READ:
        case MQTT_MSG_READ_PAYLOAD:
        {
            MqttPacketType use_packet_type;
            void* use_packet_obj;

        #ifdef WOLFMQTT_MULTITHREAD
            readLocked = 1; /* if in this state read is locked */
        #endif

            /* read payload state only happens for publish messages */
            if (*mms_stat == MQTT_MSG_READ_PAYLOAD) {
                packet_type = MQTT_PACKET_TYPE_PUBLISH;
            }

            /* Determine if we received data for this request */
            if ((wait_type == MQTT_PACKET_TYPE_ANY ||
                 wait_type == packet_type ||
                 MqttIsPubRespPacket(packet_type) == MqttIsPubRespPacket(wait_type)) &&
               (wait_packet_id == 0 || wait_packet_id == packet_id))
            {
                use_packet_obj = packet_obj;
                waitMatchFound = 1;
            }
            else {
                /* use generic packet object */
                use_packet_obj = &client->msg;
            }
            use_packet_type = packet_type;

        #ifdef WOLFMQTT_MULTITHREAD
            /* Check to see if we have a pending response for this packet */
            pendResp = NULL;
            rc = wm_SemLock(&client->lockClient);
            if (rc == 0) {
                if (MqttClient_RespList_Find(client, packet_type, packet_id,
                                                               &pendResp)) {
                    /* we found packet match this incoming read packet */
                    pendResp->packetProcessing = 1;
                    use_packet_obj = pendResp->packet_obj;
                    use_packet_type = pendResp->packet_type;
                    /* req from another thread... not a match */
                    waitMatchFound = 0;
                }
                wm_SemUnlock(&client->lockClient);
            }
            else {
                break; /* error */
            }
        #endif /* WOLFMQTT_MULTITHREAD */

            /* Perform packet handling for publish callback and QoS */
            rc = MqttClient_HandlePacket(client, use_packet_type,
                use_packet_obj, timeout_ms);

        #ifdef WOLFMQTT_NONBLOCK
            if (rc == MQTT_CODE_CONTINUE) {
                /* we have received some data, so keep the recv
                    mutex lock active and return */
                return rc;
            }
        #endif

            /* handle success case */
            if (rc >= 0) {
                rc = MQTT_CODE_SUCCESS;
            }

        #ifdef WOLFMQTT_MULTITHREAD
            if (pendResp) {
                /* Mark pending response entry done */
                if (wm_SemLock(&client->lockClient) == 0) {
                    pendResp->packetDone = 1;
                    pendResp->packet_ret = rc;
                #ifdef WOLFMQTT_DEBUG_CLIENT
                    PRINTF("PendResp Done %p", pendResp);
                #endif
                    pendResp = NULL;
                    wm_SemUnlock(&client->lockClient);
                }
            }
        #endif /* WOLFMQTT_MULTITHREAD */
            break;
        }

        case MQTT_MSG_WRITE:
        case MQTT_MSG_WRITE_PAYLOAD:
        default:
        {
        #ifdef WOLFMQTT_DEBUG_CLIENT
            PRINTF("MqttClient_WaitType: Invalid state %d!", *mms_stat);
        #endif
            rc = MQTT_CODE_ERROR_STAT;
            break;
        }
    } /* switch (*mms_stat) */

#ifdef WOLFMQTT_NONBLOCK
    if (rc != MQTT_CODE_CONTINUE)
#endif
    {
        /* reset state */
        *mms_stat = MQTT_MSG_BEGIN;
    }

#ifdef WOLFMQTT_MULTITHREAD
    if (readLocked) {
        wm_SemUnlock(&client->lockRecv);
    }
#endif
    if (rc < 0) {
    #ifdef WOLFMQTT_DEBUG_CLIENT
        PRINTF("MqttClient_WaitType: Failure: %s (%d)",
            MqttClient_ReturnCodeToString(rc), rc);
    #endif
        return rc;
    }

    if (!waitMatchFound) {
        /* if we get here, then the we are still waiting for a packet */
        goto wait_again;
    }

    return rc;
}


    private function getSwimlane()
    {
        $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));

        if (empty($swimlane)) {
            throw new PageNotFoundException();
        }

        return $swimlane;
    }


    public function whereFileName($fileName)
    {
        $this->selectSingle = $this->model->getFileNameParts($fileName);

        return $this;
    }


        private Bitmap ExtractRect(int originX, int originY, int width, int height)
        {
            // Get the desktop capture screenTexture
            var mapSource = _mDevice.ImmediateContext.MapSubresource(_desktopImageTexture, 0, MapMode.Read,
                MapFlags.None);

            // Create Drawing.Bitmap

            var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); //不能是ARGB
            var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);

            // Copy pixels from screen capture Texture to GDI bitmap
            var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
            var sourcePtr = mapSource.DataPointer;
            var destPtr = mapDest.Scan0;

            sourcePtr = IntPtr.Add(sourcePtr, originY * mapSource.RowPitch + originX * 4);
            for (var y = 0; y < height; y++)
            {
                // Copy a single line

                SharpDX.Utilities.CopyMemory(destPtr, sourcePtr, width * 4);

                // Advance pointers
                if (y != height - 1)
                    sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                destPtr = IntPtr.Add(destPtr, mapDest.Stride);
            }

            // Release source and dest locks
            bitmap.UnlockBits(mapDest);
            _mDevice.ImmediateContext.UnmapSubresource(_desktopImageTexture, 0);
            return bitmap;
        }


TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  OpContext op_context(context, node);
  TF_LITE_ENSURE_OK(context, InitializeTemporaries(context, node, &op_context));
  OpData* op_data = reinterpret_cast<OpData*>(node->user_data);

  bool adj_x = op_context.params->adj_x;
  bool adj_y = op_context.params->adj_y;

  const TfLiteTensor* lhs_data = GetInput(context, node, kInputLHSTensor);
  const TfLiteTensor* rhs_data = GetInput(context, node, kInputRHSTensor);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  // Note that quantized inference requires that all tensors have their
  // parameters set. This is usually done during quantized training.
  if (lhs_data->type == kTfLiteInt8) {
    double real_multiplier = 0.0;
    TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler(
        context, lhs_data, rhs_data, output, &real_multiplier));
    int exponent;
    QuantizeMultiplier(real_multiplier, &op_data->output_multiplier, &exponent);
    op_data->output_shift = exponent;
    // BatchMatMul has no fused activation functions. Therefore, set
    // output activation min and max to min and max of int8_t type,
    // respecitvely.
    op_data->output_activation_min = std::numeric_limits<int8_t>::min();
    op_data->output_activation_max = std::numeric_limits<int8_t>::max();
  }

  TF_LITE_ENSURE(context, lhs_data->type == kTfLiteFloat32 ||
                              lhs_data->type == kTfLiteInt8);
  TF_LITE_ENSURE(context, rhs_data->type == kTfLiteFloat32 ||
                              rhs_data->type == kTfLiteInt8);
  // Support dimensions between 2 and 4, inclusive.
  TF_LITE_ENSURE(context, NumDimensions(lhs_data) >= 2);
  TF_LITE_ENSURE(context, NumDimensions(lhs_data) <= 4);
  TF_LITE_ENSURE(context, NumDimensions(rhs_data) >= 2);
  TF_LITE_ENSURE(context, NumDimensions(rhs_data) <= 4);

  const int lhs_rank = NumDimensions(lhs_data);
  const int rhs_rank = NumDimensions(rhs_data);
  const int output_rank = std::max(lhs_rank, rhs_rank);
  const RuntimeShape extended_lhs_shape =
      RuntimeShape::ExtendedShape(output_rank, GetTensorShape(lhs_data));
  const RuntimeShape extended_rhs_shape =
      RuntimeShape::ExtendedShape(output_rank, GetTensorShape(rhs_data));

  // Ensure any batch dimensions obey broacasting rules.
  for (int i = 0; i < output_rank - 2; ++i) {
    const int lhs_dim = extended_lhs_shape.Dims(i);
    const int rhs_dim = extended_rhs_shape.Dims(i);
    if (lhs_dim != rhs_dim) {
      if (lhs_dim != 1) {
        TF_LITE_ENSURE_EQ(context, rhs_dim, 1);
      }
    }
  }
  // Ensure other dimensions work for matrix multiplication.
  int accum_dim_lhs = adj_x ? extended_lhs_shape.Dims(output_rank - 2)
                            : extended_lhs_shape.Dims(output_rank - 1);
  int accum_dim_rhs = adj_y ? extended_rhs_shape.Dims(output_rank - 1)
                            : extended_rhs_shape.Dims(output_rank - 2);

  TF_LITE_ENSURE_EQ(context, accum_dim_lhs, accum_dim_rhs);
  TfLiteStatus status =
      ResizeOutputTensor(context, extended_lhs_shape, extended_rhs_shape, adj_x,
                         adj_y, output_rank, output);
  return status;
}


  it 'should require a database' do
    expect {
      Puppet::Type.type(:mongodb_user).new({:name => 'test', :password_hash => 'pass'})
    }.to raise_error(Puppet::Error, 'Parameter \'database\' must be set')
  end


    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }


static void __net_exit sctp_net_exit(struct net *net)
{
	/* Free the local address list */
	sctp_free_addr_wq(net);
	sctp_free_local_addr_list(net);

	/* Free the control endpoint.  */
	inet_ctl_sock_destroy(net->sctp.ctl_sock);

	sctp_dbg_objcnt_exit(net);

	sctp_proc_exit(net);
	cleanup_sctp_mibs(net);
	sctp_sysctl_net_unregister(net);
}


    def initialize(seeds, options = {})
      @cluster = Cluster.new(seeds)
      @options = options
      @options[:consistency] ||= :eventual
    end


    public function transform($attr, $config, $context)
    {
        if (!isset($attr[$this->attr])) {
            return $attr;
        }

        $value = trim($attr[$this->attr]);
        unset($attr[$this->attr]);

        if (!$this->caseSensitive) {
            $value = strtolower($value);
        }

        if (!isset($this->enumToCSS[$value])) {
            return $attr;
        }
        $this->prependCSS($attr, $this->enumToCSS[$value]);
        return $attr;
    }


    public function testURIDefinitionValidation()
    {
        $parser = new HTMLPurifier_URIParser();
        $uri = $parser->parse('http://example.com');
        $this->config->set('URI.DefinitionID', 'HTMLPurifier_AttrDef_URITest->testURIDefinitionValidation');

        generate_mock_once('HTMLPurifier_URIDefinition');
        $uri_def = new HTMLPurifier_URIDefinitionMock();
        $uri_def->expectOnce('filter', array($uri, '*', '*'));
        $uri_def->returns('filter', true, array($uri, '*', '*'));
        $uri_def->expectOnce('postFilter', array($uri, '*', '*'));
        $uri_def->returns('postFilter', true, array($uri, '*', '*'));
        $uri_def->setup = true;

        // Since definitions are no longer passed by reference, we need
        // to muck around with the cache to insert our mock. This is
        // technically a little bad, since the cache shouldn't change
        // behavior, but I don't feel too good about letting users
        // overload entire definitions.
        generate_mock_once('HTMLPurifier_DefinitionCache');
        $cache_mock = new HTMLPurifier_DefinitionCacheMock();
        $cache_mock->returns('get', $uri_def);

        generate_mock_once('HTMLPurifier_DefinitionCacheFactory');
        $factory_mock = new HTMLPurifier_DefinitionCacheFactoryMock();
        $old = HTMLPurifier_DefinitionCacheFactory::instance();
        HTMLPurifier_DefinitionCacheFactory::instance($factory_mock);
        $factory_mock->returns('create', $cache_mock);

        $this->assertDef('http://example.com');

        HTMLPurifier_DefinitionCacheFactory::instance($old);
    }


private function renderPasswordForm($changedUserData, $changedEUFData )
	{
		$ns                 = e107::getRender();
		$updated_data       = e107::serialize($changedUserData,'json');
		$validation_key     = $this->getValidationKey($updated_data);
		$updated_data       = base64_encode($updated_data);
		$updated_extended   = e107::serialize($changedEUFData, 'json');
		$extended_key       = $this->getValidationKey($updated_extended);
		$updated_extended   = base64_encode($updated_extended);

		$formTarget = e107::getUrl()->create('user/myprofile/edit');

		$text = "<form method='post' action='".$formTarget."'>

";

				foreach ($_POST as $k => $v)
				{
					if (is_array($v))
					{
						foreach ($v as $sk => $sv)
						{
							$text .= "<input type='hidden' name='{$k}[{$sk}]' value='{$sv}' />\n";
						}
					}
					else
					{
						$text .= "<input type='hidden' name='{$k}' value='{$v}' />\n";
					}
				}

				$text .= LAN_USET_21."

				<input type='password' class='form-control' name='currentpassword' value='' size='30' />";

				$text .= "
				<input type='hidden' name='updated_data' value='{$updated_data}' />
				<input type='hidden' name='updated_key' value='{$validation_key}' />
				<input type='hidden' name='updated_extended' value='{$updated_extended}' />
				<input type='hidden' name='extended_key' value='{$extended_key}' />
				<input type='hidden' name='e-token' value='".defset('e_TOKEN')."' />

				".e107::getForm()->button('SaveValidatedInfo',1, 'submit', LAN_ENTER)."

			</form>";

			$ns->tablerender(LAN_USET_39, $text);

	}


      function onClose() {
        assert(++state.closes <= 3,
               makeMsg('Wrong close count: ' + state.closes));
        if (state.closes === 2)
          server.close();
        else if (state.closes === 3)
          next();
      }


    public function testCaptionConvertAlignLeft()
    {
        $this->assertResult(
            '<caption align="left" />',
            '<caption style="text-align:left;" />'
        );
    }


  public DropFileContainer(final String id, final String mimeType) {
    super(id);
    this.mimeType = mimeType;
    main = new WebMarkupContainer("main");
    add(main);
  }


			array_push($newgroupprivs, $type);
	}
	if(empty($newgroupprivs) || (count($newgroupprivs) == 1 &&
           in_array("cascade", $newgroupprivs))) {
		return array('status' => 'error',
                    'errorcode' => 53,
                    'errormsg' => 'Invalid or missing permissions list supplied');
	}
    updateUserOrGroupPrivs($groupid, $nodeid, $newgroupprivs, array(), "group");
	return array('status' => 'success');
}


    public function setUp()
    {
        $this->cleanup = [];
    }


  _size ({ id, token }, done) {
    return this.client
      .get(`https://graph.instagram.com/${id}`)
      .qs({ fields: 'media_url' })
      .auth(token)
      .request((err, resp, body) => {
        if (err || resp.statusCode !== 200) {
          err = this._error(err, resp)
          logger.error(err, 'provider.instagram.size.error')
          return done(err)
        }

        getURLMeta(body.media_url)
          .then(({ size }) => done(null, size))
          .catch((err2) => {
            logger.error(err2, 'provider.instagram.size.error')
            done(err2)
          })
      })
  }


    public function execute($image)
    {
        $amount = $this->argument(0)->between(0, 100)->value(1);

        for ($i=0; $i < intval($amount); $i++) {
            imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR);
        }

        return true;
    }


static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	struct perf_event *event = file->private_data;
	struct perf_event_context *ctx;
	long ret;

	ctx = perf_event_ctx_lock(event);
	ret = _perf_ioctl(event, cmd, arg);
	perf_event_ctx_unlock(event, ctx);

	return ret;
}


static void WriteProfile(j_compress_ptr jpeg_info,Image *image)
{
  const char
    *name;

  const StringInfo
    *profile;

  MagickBooleanType
    iptc;

  register ssize_t
    i;

  size_t
    length,
    tag_length;

  StringInfo
    *custom_profile;

  /*
    Save image profile as a APP marker.
  */
  iptc=MagickFalse;
  custom_profile=AcquireStringInfo(65535L);
  ResetImageProfileIterator(image);
  for (name=GetNextImageProfile(image); name != (const char *) NULL; )
  {
    profile=GetImageProfile(image,name);
    if (LocaleCompare(name,"EXIF") == 0)
      for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L)
      {
        length=MagickMin(GetStringInfoLength(profile)-i,65533L);
        jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i,
          (unsigned int) length);
      }
    if (LocaleCompare(name,"ICC") == 0)
      {
        register unsigned char
          *p;

        tag_length=strlen(ICC_PROFILE);
        p=GetStringInfoDatum(custom_profile);
        (void) CopyMagickMemory(p,ICC_PROFILE,tag_length);
        p[tag_length]='\0';
        for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)
        {
          length=MagickMin(GetStringInfoLength(profile)-i,65519L);
          p[12]=(unsigned char) ((i/65519L)+1);
          p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);
          (void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,
            length);
          jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(
            custom_profile),(unsigned int) (length+tag_length+3));
        }
      }
    if (((LocaleCompare(name,"IPTC") == 0) ||
        (LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse))
      {
        register unsigned char
          *p;

        size_t
          roundup;

        iptc=MagickTrue;
        p=GetStringInfoDatum(custom_profile);
        for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)
        {
          length=MagickMin(GetStringInfoLength(profile)-i,65500L);
          roundup=(size_t) (length & 0x01);
          if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0)
            {
              (void) memcpy(p,"Photoshop 3.0 ",14);
              tag_length=14;
            }
          else
            {
              (void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
              tag_length=26;
              p[24]=(unsigned char) (length >> 8);
              p[25]=(unsigned char) (length & 0xff);
            }
          p[13]=0x00;
          (void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);
          if (roundup != 0)
            p[length+tag_length]='\0';
          jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(
            custom_profile),(unsigned int) (length+tag_length+roundup));
        }
      }
    if (LocaleCompare(name,"XMP") == 0)
      {
        StringInfo
          *xmp_profile;

        /*
          Add namespace to XMP profile.
        */
        xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ ");
        if (xmp_profile != (StringInfo *) NULL)
          {
            if (profile != (StringInfo *) NULL)
              ConcatenateStringInfo(xmp_profile,profile);
            GetStringInfoDatum(xmp_profile)[28]='\0';
            for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)
            {
              length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);
              jpeg_write_marker(jpeg_info,XML_MARKER,
                GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);
            }
            xmp_profile=DestroyStringInfo(xmp_profile);
          }
      }
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      "%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile));
    name=GetNextImageProfile(image);
  }
  custom_profile=DestroyStringInfo(custom_profile);
}


func (m *MockTokenRevocationStorage) RevokeRefreshToken(arg0 context.Context, arg1 string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "RevokeRefreshToken", arg0, arg1)
	ret0, _ := ret[0].(error)
	return ret0
}


    public function pathTestNoAuthority()
    {
        return [
            // path-rootless
            ['urn:example:animal:ferret:nose'],
            // path-absolute
            ['urn:/example:animal:ferret:nose'],
            ['urn:/'],
            // path-empty
            ['urn:'],
            ['urn'],
        ];
    }


int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
{
	int m;

	/* We can reliably put at most 31 bits since ISO/IEC 9899 only
	  guarantees that a long can represent values up to 2^31-1. */
	//assert(n >= 0 && n < 32);
	if (n < 0 || n >= 32) {
		return EOF;
	}
	/* Ensure that only the bits to be output are nonzero. */
	assert(!(v & (~JAS_ONES(n))));

	/* Put the desired number of bits to the specified bit stream. */
	m = n - 1;
	while (--n >= 0) {
		if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
			return EOF;
		}
		v <<= 1;
	}
	return 0;
}


func validateAndUpdateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) {
	c.Data["Webhook"] = w

	if c.HasError() {
		c.Success(orCtx.TmplNew)
		return
	}

	field, msg, ok := validateWebhook(c.User, c.Locale, w)
	if !ok {
		c.FormErr(field)
		c.RenderWithErr(msg, orCtx.TmplNew, nil)
		return
	}

	if err := w.UpdateEvent(); err != nil {
		c.Error(err, "update event")
		return
	} else if err := db.UpdateWebhook(w); err != nil {
		c.Error(err, "update webhook")
		return
	}

	c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
	c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
}


mark_source_chains(const struct xt_table_info *newinfo,
		   unsigned int valid_hooks, void *entry0)
{
	unsigned int hook;

	/* No recursion; use packet counter to save back ptrs (reset
	   to 0 as we leave), and comefrom to save source hook bitmask */
	for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
		unsigned int pos = newinfo->hook_entry[hook];
		struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);

		if (!(valid_hooks & (1 << hook)))
			continue;

		/* Set initial back pointer. */
		e->counters.pcnt = pos;

		for (;;) {
			const struct xt_standard_target *t
				= (void *)ipt_get_target_c(e);
			int visited = e->comefrom & (1 << hook);

			if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
				pr_err("iptables: loop hook %u pos %u %08X.\n",
				       hook, pos, e->comefrom);
				return 0;
			}
			e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));

			/* Unconditional return/END. */
			if ((unconditional(e) &&
			     (strcmp(t->target.u.user.name,
				     XT_STANDARD_TARGET) == 0) &&
			     t->verdict < 0) || visited) {
				unsigned int oldpos, size;

				if ((strcmp(t->target.u.user.name,
					    XT_STANDARD_TARGET) == 0) &&
				    t->verdict < -NF_MAX_VERDICT - 1) {
					duprintf("mark_source_chains: bad "
						"negative verdict (%i)\n",
								t->verdict);
					return 0;
				}

				/* Return: backtrack through the last
				   big jump. */
				do {
					e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
					if (e->comefrom
					    & (1 << NF_INET_NUMHOOKS)) {
						duprintf("Back unset "
							 "on hook %u "
							 "rule %u\n",
							 hook, pos);
					}
#endif
					oldpos = pos;
					pos = e->counters.pcnt;
					e->counters.pcnt = 0;

					/* We're at the start. */
					if (pos == oldpos)
						goto next;

					e = (struct ipt_entry *)
						(entry0 + pos);
				} while (oldpos == pos + e->next_offset);

				/* Move along one */
				size = e->next_offset;
				e = (struct ipt_entry *)
					(entry0 + pos + size);
				e->counters.pcnt = pos;
				pos += size;
			} else {
				int newpos = t->verdict;

				if (strcmp(t->target.u.user.name,
					   XT_STANDARD_TARGET) == 0 &&
				    newpos >= 0) {
					if (newpos > newinfo->size -
						sizeof(struct ipt_entry)) {
						duprintf("mark_source_chains: "
							"bad verdict (%i)\n",
								newpos);
						return 0;
					}
					/* This a jump; chase it. */
					duprintf("Jump rule %u -> %u\n",
						 pos, newpos);
				} else {
					/* ... this is a fallthru */
					newpos = pos + e->next_offset;
				}
				e = (struct ipt_entry *)
					(entry0 + newpos);
				e->counters.pcnt = pos;
				pos = newpos;
			}
		}
next:
		duprintf("Finished chain %u\n", hook);
	}
	return 1;
}


    public void translate(ServerSpawnPaintingPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());

        PaintingEntity entity = new PaintingEntity(packet.getEntityId(),
                session.getEntityCache().getNextEntityId().incrementAndGet(),
                position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal());

        session.getEntityCache().spawnEntity(entity);
    }


    public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);

        if ($tag['project_id'] != $project['id']) {
            throw new AccessForbiddenException();
        }

        if ($this->tagModel->remove($tag_id)) {
            $this->flash->success(t('Tag removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this tag.'));
        }

        $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));
    }


                        foreach ($days as $event) {
                            if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))
                                break;
                            if (empty($event->eventstart))
                                $event->eventstart = $event->eventdate->date;
                            $extitem[] = $event;
                        }


callback : function() { remove(hash); save(); }


ast2obj_type_ignore(void* _o)
{
    type_ignore_ty o = (type_ignore_ty)_o;
    PyObject *result = NULL, *value = NULL;
    if (!o) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    switch (o->kind) {
    case TypeIgnore_kind:
        result = PyType_GenericNew(TypeIgnore_type, NULL, NULL);
        if (!result) goto failed;
        value = ast2obj_int(o->v.TypeIgnore.lineno);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_lineno, value) == -1)
            goto failed;
        Py_DECREF(value);
        break;
    }
    return result;
failed:
    Py_XDECREF(value);
    Py_XDECREF(result);
    return NULL;
}


      it "returns nil" do
        config.logger.should be_nil
      end


	std::string bdecode_error_category::message(int ev) const BOOST_SYSTEM_NOEXCEPT
	{
		static char const* msgs[] =
		{
			"no error",
			"expected string in bencoded string",
			"expected colon in bencoded string",
			"unexpected end of file in bencoded string",
			"expected value (list, dict, int or string) in bencoded string",
			"bencoded nesting depth exceeded",
			"bencoded item count limit exceeded",
			"integer overflow",
		};
		if (ev < 0 || ev >= int(sizeof(msgs)/sizeof(msgs[0])))
			return "Unknown error";
		return msgs[ev];
	}


    function getUsername()
    {
        if (isset($this->session['username'])) {
            return($this->session['username']);
        }
        return('');
    }


def send_note_attachment(filename):
    """Return a file from the note attachment directory"""
    file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)
    if file_path is not None:
        try:
            return send_file(file_path, as_attachment=True)
        except Exception:
            logger.exception("Send note attachment")


static int recv_stream(struct kiocb *iocb, struct socket *sock,
		       struct msghdr *m, size_t buf_len, int flags)
{
	struct sock *sk = sock->sk;
	struct tipc_port *tport = tipc_sk_port(sk);
	struct sk_buff *buf;
	struct tipc_msg *msg;
	long timeout;
	unsigned int sz;
	int sz_to_copy, target, needed;
	int sz_copied = 0;
	u32 err;
	int res = 0;

	/* Catch invalid receive attempts */
	if (unlikely(!buf_len))
		return -EINVAL;

	lock_sock(sk);

	if (unlikely((sock->state == SS_UNCONNECTED))) {
		res = -ENOTCONN;
		goto exit;
	}

	/* will be updated in set_orig_addr() if needed */
	m->msg_namelen = 0;

	target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

restart:
	/* Look for a message in receive queue; wait if necessary */
	while (skb_queue_empty(&sk->sk_receive_queue)) {
		if (sock->state == SS_DISCONNECTING) {
			res = -ENOTCONN;
			goto exit;
		}
		if (timeout <= 0L) {
			res = timeout ? timeout : -EWOULDBLOCK;
			goto exit;
		}
		release_sock(sk);
		timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
							   tipc_rx_ready(sock),
							   timeout);
		lock_sock(sk);
	}

	/* Look at first message in receive queue */
	buf = skb_peek(&sk->sk_receive_queue);
	msg = buf_msg(buf);
	sz = msg_data_sz(msg);
	err = msg_errcode(msg);

	/* Discard an empty non-errored message & try again */
	if ((!sz) && (!err)) {
		advance_rx_queue(sk);
		goto restart;
	}

	/* Optionally capture sender's address & ancillary data of first msg */
	if (sz_copied == 0) {
		set_orig_addr(m, msg);
		res = anc_data_recv(m, msg, tport);
		if (res)
			goto exit;
	}

	/* Capture message data (if valid) & compute return value (always) */
	if (!err) {
		u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);

		sz -= offset;
		needed = (buf_len - sz_copied);
		sz_to_copy = (sz <= needed) ? sz : needed;

		res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
					      m->msg_iov, sz_to_copy);
		if (res)
			goto exit;

		sz_copied += sz_to_copy;

		if (sz_to_copy < sz) {
			if (!(flags & MSG_PEEK))
				TIPC_SKB_CB(buf)->handle =
				(void *)(unsigned long)(offset + sz_to_copy);
			goto exit;
		}
	} else {
		if (sz_copied != 0)
			goto exit; /* can't add error msg to valid data */

		if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
			res = 0;
		else
			res = -ECONNRESET;
	}

	/* Consume received message (optional) */
	if (likely(!(flags & MSG_PEEK))) {
		if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
			tipc_acknowledge(tport->ref, tport->conn_unacked);
		advance_rx_queue(sk);
	}

	/* Loop around if more data is required */
	if ((sz_copied < buf_len) &&	/* didn't get all requested data */
	    (!skb_queue_empty(&sk->sk_receive_queue) ||
	    (sz_copied < target)) &&	/* and more is ready or required */
	    (!(flags & MSG_PEEK)) &&	/* and aren't just peeking at data */
	    (!err))			/* and haven't reached a FIN */
		goto restart;

exit:
	release_sock(sk);
	return sz_copied ? sz_copied : res;
}


    public function testCaptionConvertAlignTop()
    {
        $this->assertResult(
            '<caption align="top" />',
            '<caption style="caption-side:top;" />'
        );
    }


ga_init2(garray_T *gap, int itemsize, int growsize)
{
    ga_init(gap);
    gap->ga_itemsize = itemsize;
    gap->ga_growsize = growsize;
}


        public PBEWithSHA256AESCBC256()
        {
            super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA256, 256, 16);
        }


    it 'should have muppet named mspiggy' do
      expect(subject.call(['muppet', 'mspiggy'])).to be_truthy
    end


    public function clearTag($name)
    {
        unset($this->tags[$name]);

        return $this;
    }


_PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize)
{
    /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL
       for calloc(0, 0), which would be treated as an error. Some platforms
       would return a pointer with no memory behind it, which would break
       pymalloc.  To solve these problems, allocate an extra byte. */
    if (nelem == 0 || elsize == 0) {
        nelem = 1;
        elsize = 1;
    }
    return calloc(nelem, elsize);
}


  def test_full_sanitize_respect_html_escaping_of_the_given_string
    assert_equal 'test\r\nstring', full_sanitize('test\r\nstring')
    assert_equal '&', full_sanitize('&')
    assert_equal '&', full_sanitize('&')
    assert_equal '&amp;', full_sanitize('&amp;')
    assert_equal 'omg <script>BOM</script>', full_sanitize('omg <script>BOM</script>')
  end


    public function getLastEvent()
    {
        return $this->lastEvent;
    }


    function listUsers()
    {
        $this->log('Auth_Container_SMBPasswd::fetchData() called.', AUTH_LOG_DEBUG);
        return $this->pwfile->getAccounts();
    }


function cmdSet(key, val) {
  var objVal = val;

  try {
    var strTest = /^[\'\"](.*?)[\'\"]$/.exec(val);
    if (!strTest || strTest.length !== 2) { // do not parse if explicitly a string
      objVal = eval('(' + val + ')'); // attempt to parse
    } else {
      objVal = strTest[1];
    }
  } catch(ex) {
    // use as existing string
  }

  instance.setProp(key, objVal);
  rl.write(': stored as type ' + typeof objVal);

  enterCommand();
}


def _configuration_ldap_helper(to_save):
    reboot_required = False
    reboot_required |= _config_string(to_save, "config_ldap_provider_url")
    reboot_required |= _config_int(to_save, "config_ldap_port")
    reboot_required |= _config_int(to_save, "config_ldap_authentication")
    reboot_required |= _config_string(to_save, "config_ldap_dn")
    reboot_required |= _config_string(to_save, "config_ldap_serv_username")
    reboot_required |= _config_string(to_save, "config_ldap_user_object")
    reboot_required |= _config_string(to_save, "config_ldap_group_object_filter")
    reboot_required |= _config_string(to_save, "config_ldap_group_members_field")
    reboot_required |= _config_string(to_save, "config_ldap_member_user_object")
    reboot_required |= _config_checkbox(to_save, "config_ldap_openldap")
    reboot_required |= _config_int(to_save, "config_ldap_encryption")
    reboot_required |= _config_string(to_save, "config_ldap_cacert_path")
    reboot_required |= _config_string(to_save, "config_ldap_cert_path")
    reboot_required |= _config_string(to_save, "config_ldap_key_path")
    _config_string(to_save, "config_ldap_group_name")
    if to_save.get("config_ldap_serv_password", "") != "":
        reboot_required |= 1
        config.set_from_dictionary(to_save, "config_ldap_serv_password", base64.b64encode, encode='UTF-8')
    config.save()

    if not config.config_ldap_provider_url \
        or not config.config_ldap_port \
        or not config.config_ldap_dn \
            or not config.config_ldap_user_object:
        return reboot_required, _configuration_result(_('Please Enter a LDAP Provider, '
                                                        'Port, DN and User Object Identifier'))

    if config.config_ldap_authentication > constants.LDAP_AUTH_ANONYMOUS:
        if config.config_ldap_authentication > constants.LDAP_AUTH_UNAUTHENTICATE:
            if not config.config_ldap_serv_username or not bool(config.config_ldap_serv_password):
                return reboot_required, _configuration_result(_('Please Enter a LDAP Service Account and Password'))
        else:
            if not config.config_ldap_serv_username:
                return reboot_required, _configuration_result(_('Please Enter a LDAP Service Account'))

    if config.config_ldap_group_object_filter:
        if config.config_ldap_group_object_filter.count("%s") != 1:
            return reboot_required, \
                   _configuration_result(_('LDAP Group Object Filter Needs to Have One "%s" Format Identifier'))
        if config.config_ldap_group_object_filter.count("(") != config.config_ldap_group_object_filter.count(")"):
            return reboot_required, _configuration_result(_('LDAP Group Object Filter Has Unmatched Parenthesis'))

    if config.config_ldap_user_object.count("%s") != 1:
        return reboot_required, \
               _configuration_result(_('LDAP User Object Filter needs to Have One "%s" Format Identifier'))
    if config.config_ldap_user_object.count("(") != config.config_ldap_user_object.count(")"):
        return reboot_required, _configuration_result(_('LDAP User Object Filter Has Unmatched Parenthesis'))

    if to_save.get("ldap_import_user_filter") == '0':
        config.config_ldap_member_user_object = ""
    else:
        if config.config_ldap_member_user_object.count("%s") != 1:
            return reboot_required, \
                   _configuration_result(_('LDAP Member User Filter needs to Have One "%s" Format Identifier'))
        if config.config_ldap_member_user_object.count("(") != config.config_ldap_member_user_object.count(")"):
            return reboot_required, _configuration_result(_('LDAP Member User Filter Has Unmatched Parenthesis'))

    if config.config_ldap_cacert_path or config.config_ldap_cert_path or config.config_ldap_key_path:
        if not (os.path.isfile(config.config_ldap_cacert_path) and
                os.path.isfile(config.config_ldap_cert_path) and
                os.path.isfile(config.config_ldap_key_path)):
            return reboot_required, \
                   _configuration_result(_('LDAP CACertificate, Certificate or Key Location is not Valid, '
                                           'Please Enter Correct Path'))
    return reboot_required, None


            $comments->records[$key]->avatar = $db->selectObject('user_avatar',"user_id='".$record->poster."'");
        }

        if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);
        // eDebug($sql, true);

        // count the unapproved comments
        if ($require_approval == 1 && $user->isAdmin()) {
            $sql  = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';
            $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';
            $sql .= 'WHERE cnt.content_id='.$this->params['content_id']." AND cnt.content_type='".$this->params['content_type']."' ";
            $sql .= 'AND com.approved=0';
            $unapproved = $db->countObjectsBySql($sql);
        } else {
            $unapproved = 0;
        }

        $this->config = $this->params['config'];
        $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');
        $ratings = !empty($this->params['ratings']) ? true : false;

        assign_to_template(array(
            'comments'=>$comments,
            'config'=>$this->params['config'],
            'unapproved'=>$unapproved,
			'content_id'=>$this->params['content_id'],
			'content_type'=>$this->params['content_type'],
			'user'=>$user,
			'hideform'=>$this->params['hideform'],
			'hidecomments'=>$this->params['hidecomments'],
			'title'=>$this->params['title'],
			'formtitle'=>$this->params['formtitle'],
            'type'=>$type,
            'ratings'=>$ratings,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
		));
	}


  def validate_privs(set_privs, all_privs)
    all_privs = all_privs.collect { |p| p.downcase }
    set_privs = set_privs.collect { |p| p.downcase }
    invalid_privs = Array.new
    hints = Array.new
    # Test each of the user provided privs to see if they exist in all_privs
    set_privs.each do |priv|
      invalid_privs << priv unless all_privs.include?(priv)
      hints << "#{priv}_priv" if all_privs.include?("#{priv}_priv")
    end
    unless invalid_privs.empty?
      # Print a decently helpful and gramatically correct error message
      hints = "Did you mean '#{hints.join(',')}'?" unless hints.empty?
      p = invalid_privs.size > 1 ? ['s', 'are not valid'] : ['', 'is not valid']
      detail = ["The privilege#{p[0]} '#{invalid_privs.join(',')}' #{p[1]}."]
      fail [detail, hints].join(' ')
    end
  end


    public static function set($vars)
    {
        self::set_session($vars);
    }


    function edit_freeform() {
        $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
        if ($section->parent == -1) {
            notfoundController::handle_not_found();
            exit;
        } // doesn't work for standalone pages
        if (empty($section->id)) {
            $section->public = 1;
            if (!isset($section->parent)) {
                // This is another precaution.  The parent attribute
                // should ALWAYS be set by the caller.
                //FJD - if that's the case, then we should die.
                notfoundController::handle_not_authorized();
                exit;
                //$section->parent = 0;
            }
        }
        assign_to_template(array(
            'section' => $section,
            'glyphs' => self::get_glyphs(),
        ));
    }


    def setUp(self):

        self.http_client = Mock()
        self.reactor = ThreadedMemoryReactorClock()
        self.hs_clock = Clock(self.reactor)
        self.homeserver = setup_test_homeserver(
            self.addCleanup,
            federation_http_client=self.http_client,
            clock=self.hs_clock,
            reactor=self.reactor,
        )

        user_id = UserID("us", "test")
        our_user = create_requester(user_id)
        room_creator = self.homeserver.get_room_creation_handler()
        self.room_id = self.get_success(
            room_creator.create_room(
                our_user, room_creator._presets_dict["public_chat"], ratelimit=False
            )
        )[0]["room_id"]

        self.store = self.homeserver.get_datastore()

        # Figure out what the most recent event is
        most_recent = self.get_success(
            self.homeserver.get_datastore().get_latest_event_ids_in_room(self.room_id)
        )[0]

        join_event = make_event_from_dict(
            {
                "room_id": self.room_id,
                "sender": "@baduser:test.serv",
                "state_key": "@baduser:test.serv",
                "event_id": "$join:test.serv",
                "depth": 1000,
                "origin_server_ts": 1,
                "type": "m.room.member",
                "origin": "test.servx",
                "content": {"membership": "join"},
                "auth_events": [],
                "prev_state": [(most_recent, {})],
                "prev_events": [(most_recent, {})],
            }
        )

        self.handler = self.homeserver.get_federation_handler()
        self.handler.do_auth = lambda origin, event, context, auth_events: succeed(
            context
        )
        self.client = self.homeserver.get_federation_client()
        self.client._check_sigs_and_hash_and_fetch = lambda dest, pdus, **k: succeed(
            pdus
        )

        # Send the join, it should return None (which is not an error)
        self.assertEqual(
            self.get_success(
                self.handler.on_receive_pdu(
                    "test.serv", join_event, sent_to_us_directly=True
                )
            ),
            None,
        )

        # Make sure we actually joined the room
        self.assertEqual(
            self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))[0],
            "$join:test.serv",
        )


    it "should match providers to resources" do
      provider = mock("ssl_provider", :name => "ssl")
      resource = mock("ssl_resource")
      resource.expects(:provider=).with(provider)

      provider_class.expects(:instances).returns([provider])
      provider_class.prefetch("ssl" => resource)
    end


gplotGenCommandFile(GPLOT  *gplot)
{
char     buf[L_BUFSIZE];
char    *cmdstr, *plottitle, *dataname;
l_int32  i, plotstyle, nplots;
FILE    *fp;

    PROCNAME("gplotGenCommandFile");

    if (!gplot)
        return ERROR_INT("gplot not defined", procName, 1);

        /* Remove any previous command data */
    sarrayClear(gplot->cmddata);

        /* Generate command data instructions */
    if (gplot->title) {   /* set title */
        snprintf(buf, L_BUFSIZE, "set title '%s'", gplot->title);
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }
    if (gplot->xlabel) {   /* set xlabel */
        snprintf(buf, L_BUFSIZE, "set xlabel '%s'", gplot->xlabel);
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }
    if (gplot->ylabel) {   /* set ylabel */
        snprintf(buf, L_BUFSIZE, "set ylabel '%s'", gplot->ylabel);
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }

        /* Set terminal type and output */
    if (gplot->outformat == GPLOT_PNG) {
        snprintf(buf, L_BUFSIZE, "set terminal png; set output '%s'",
                 gplot->outname);
    } else if (gplot->outformat == GPLOT_PS) {
        snprintf(buf, L_BUFSIZE, "set terminal postscript; set output '%s'",
                 gplot->outname);
    } else if (gplot->outformat == GPLOT_EPS) {
        snprintf(buf, L_BUFSIZE,
                 "set terminal postscript eps; set output '%s'",
                 gplot->outname);
    } else if (gplot->outformat == GPLOT_LATEX) {
        snprintf(buf, L_BUFSIZE, "set terminal latex; set output '%s'",
                 gplot->outname);
    }
    sarrayAddString(gplot->cmddata, buf, L_COPY);

    if (gplot->scaling == GPLOT_LOG_SCALE_X ||
        gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
        snprintf(buf, L_BUFSIZE, "set logscale x");
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }
    if (gplot->scaling == GPLOT_LOG_SCALE_Y ||
        gplot->scaling == GPLOT_LOG_SCALE_X_Y) {
        snprintf(buf, L_BUFSIZE, "set logscale y");
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }

    nplots = sarrayGetCount(gplot->datanames);
    for (i = 0; i < nplots; i++) {
        plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY);
        dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY);
        numaGetIValue(gplot->plotstyles, i, &plotstyle);
        if (nplots == 1) {
            snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s",
                     dataname, plottitle, gplotstylenames[plotstyle]);
        } else {
            if (i == 0)
                snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s, \\",
                     dataname, plottitle, gplotstylenames[plotstyle]);
            else if (i < nplots - 1)
                snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s, \\",
                     dataname, plottitle, gplotstylenames[plotstyle]);
            else
                snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s",
                     dataname, plottitle, gplotstylenames[plotstyle]);
        }
        sarrayAddString(gplot->cmddata, buf, L_COPY);
    }

        /* Write command data to file */
    cmdstr = sarrayToString(gplot->cmddata, 1);
    if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) {
        LEPT_FREE(cmdstr);
        return ERROR_INT("cmd stream not opened", procName, 1);
    }
    fwrite(cmdstr, 1, strlen(cmdstr), fp);
    fclose(fp);
    LEPT_FREE(cmdstr);
    return 0;
}


int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,
		   struct sockaddr_storage *kern_address, int mode)
{
	int tot_len;

	if (kern_msg->msg_namelen) {
		if (mode == VERIFY_READ) {
			int err = move_addr_to_kernel(kern_msg->msg_name,
						      kern_msg->msg_namelen,
						      kern_address);
			if (err < 0)
				return err;
		}
		if (kern_msg->msg_name)
			kern_msg->msg_name = kern_address;
	} else
		kern_msg->msg_name = NULL;

	tot_len = iov_from_user_compat_to_kern(kern_iov,
					  (struct compat_iovec __user *)kern_msg->msg_iov,
					  kern_msg->msg_iovlen);
	if (tot_len >= 0)
		kern_msg->msg_iov = kern_iov;

	return tot_len;
}


TagSearch.prototype.getSort = function() {
    //todo: read it off the page
    var link = $('.tabBar a.on');
    if (link.length === 1) {
        var sort = link.attr('id').replace('sort_', '');
        if (sort === 'name' || sort === 'used') {
            return sort;
        }
    }
    return 'name';
};


key_ref_t key_create_or_update(key_ref_t keyring_ref,
			       const char *type,
			       const char *description,
			       const void *payload,
			       size_t plen,
			       key_perm_t perm,
			       unsigned long flags)
{
	struct keyring_index_key index_key = {
		.description	= description,
	};
	struct key_preparsed_payload prep;
	struct assoc_array_edit *edit;
	const struct cred *cred = current_cred();
	struct key *keyring, *key = NULL;
	key_ref_t key_ref;
	int ret;

	/* look up the key type to see if it's one of the registered kernel
	 * types */
	index_key.type = key_type_lookup(type);
	if (IS_ERR(index_key.type)) {
		key_ref = ERR_PTR(-ENODEV);
		goto error;
	}

	key_ref = ERR_PTR(-EINVAL);
	if (!index_key.type->match || !index_key.type->instantiate ||
	    (!index_key.description && !index_key.type->preparse))
		goto error_put_type;

	keyring = key_ref_to_ptr(keyring_ref);

	key_check(keyring);

	key_ref = ERR_PTR(-ENOTDIR);
	if (keyring->type != &key_type_keyring)
		goto error_put_type;

	memset(&prep, 0, sizeof(prep));
	prep.data = payload;
	prep.datalen = plen;
	prep.quotalen = index_key.type->def_datalen;
	prep.trusted = flags & KEY_ALLOC_TRUSTED;
	prep.expiry = TIME_T_MAX;
	if (index_key.type->preparse) {
		ret = index_key.type->preparse(&prep);
		if (ret < 0) {
			key_ref = ERR_PTR(ret);
			goto error_free_prep;
		}
		if (!index_key.description)
			index_key.description = prep.description;
		key_ref = ERR_PTR(-EINVAL);
		if (!index_key.description)
			goto error_free_prep;
	}
	index_key.desc_len = strlen(index_key.description);

	key_ref = ERR_PTR(-EPERM);
	if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags))
		goto error_free_prep;
	flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0;

	ret = __key_link_begin(keyring, &index_key, &edit);
	if (ret < 0) {
		key_ref = ERR_PTR(ret);
		goto error_free_prep;
	}

	/* if we're going to allocate a new key, we're going to have
	 * to modify the keyring */
	ret = key_permission(keyring_ref, KEY_NEED_WRITE);
	if (ret < 0) {
		key_ref = ERR_PTR(ret);
		goto error_link_end;
	}

	/* if it's possible to update this type of key, search for an existing
	 * key of the same type and description in the destination keyring and
	 * update that instead if possible
	 */
	if (index_key.type->update) {
		key_ref = find_key_to_update(keyring_ref, &index_key);
		if (key_ref)
			goto found_matching_key;
	}

	/* if the client doesn't provide, decide on the permissions we want */
	if (perm == KEY_PERM_UNDEF) {
		perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
		perm |= KEY_USR_VIEW;

		if (index_key.type->read)
			perm |= KEY_POS_READ;

		if (index_key.type == &key_type_keyring ||
		    index_key.type->update)
			perm |= KEY_POS_WRITE;
	}

	/* allocate a new key */
	key = key_alloc(index_key.type, index_key.description,
			cred->fsuid, cred->fsgid, cred, perm, flags);
	if (IS_ERR(key)) {
		key_ref = ERR_CAST(key);
		goto error_link_end;
	}

	/* instantiate it and link it into the target keyring */
	ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
	if (ret < 0) {
		key_put(key);
		key_ref = ERR_PTR(ret);
		goto error_link_end;
	}

	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));

error_link_end:
	__key_link_end(keyring, &index_key, edit);
error_free_prep:
	if (index_key.type->preparse)
		index_key.type->free_preparse(&prep);
error_put_type:
	key_type_put(index_key.type);
error:
	return key_ref;

 found_matching_key:
	/* we found a matching key, so we're going to try to update it
	 * - we can drop the locks first as we have the key pinned
	 */
	__key_link_end(keyring, &index_key, edit);

	key_ref = __key_update(key_ref, &prep);
	goto error_free_prep;
}


function addGroup($data) {
	if($data['editgroupid'] == 0 || $data['editgroupid'] == '')
		$data['editgroupid'] = 'NULL';
	if($data['type'] == "user") {
		if(! array_key_exists('custom', $data))
			$data['custom'] = 1;
		elseif($data['custom'] == 0) {
			$ownerid = 'NULL';
			$data['editgroupid'] = 'NULL';
		}
		if($data['custom'])
			$ownerid = getUserlistID($data['owner']);
		$query = "INSERT INTO usergroup "
				 .         "(name, "
				 .         "affiliationid, "
				 .         "ownerid, "
				 .         "editusergroupid, "
		       .         "custom, "
		       .         "initialmaxtime, "
		       .         "totalmaxtime, ";
		if(checkUserHasPerm('Set Overlapping Reservation Count'))
			$query .=     "overlapResCount, ";
		$query .=        "maxextendtime) "
				 . "VALUES ('{$data['name']}', "
				 .        "{$data['affiliationid']}, "
				 .        "$ownerid, "
				 .        "{$data['editgroupid']}, "
		       .        "{$data['custom']}, "
		       .        "{$data['initialmax']}, "
		       .        "{$data['totalmax']}, ";
		if(checkUserHasPerm('Set Overlapping Reservation Count'))
			$query .=    "{$data['overlap']}, ";
		$query .=       "{$data['maxextend']})";
	}
	else {
		$query = "INSERT INTO resourcegroup "
				 .         "(name, "
				 .         "ownerusergroupid, "
		       .         "resourcetypeid) "
				 . "VALUES ('{$data['name']}', "
		       .         "{$data['ownergroup']}, "
		       .         "'{$data['resourcetypeid']}')";
	}
	$qh = doQuery($query, 305);
	clearPrivCache();
	return mysql_affected_rows($GLOBALS['mysql_link_vcl']);
}


module.exports = function(test) {

    let client;
    describe("SNAC Testing client accessing service before session is activated ", function() {

        beforeEach(function(done) {
            client = OPCUAClient.create();
            done();
        });
        afterEach(function(done) {
            client = null;
            done();
        });

        it("SNAC1- should return BadSessionNotActivated when service is called before session is activated", (done) => {

            let session1;
            let last_response;
            let last_response_err;
            let activate_error;
            async.series([

                function(callback) {
                    client.connect(test.endpointUrl, callback);
                },
                function(callback) {
                    client._createSession(function(err, session) {
                        if (err) {
                            return callback(err);
                        }
                        session1 = session;
                        callback();
                    });
                },
                // let verify that it is now possible to send a request on client1's session
                function(callback) {
                    // coerce nodeIds
                    const request = new ReadRequest({
                        nodesToRead: [{ nodeId: "i=2255", attributeId: 13 }],
                        maxAge: 0,
                        timestampsToReturn: TimestampsToReturn.Both
                    });
                    request.requestHeader.authenticationToken = session1.authenticationToken;

                    client.performMessageTransaction(request, function(err, response) {
                        console.log(err ? err.toString() : "null");
                        console.log(response ? response.toString() : "null");
                        last_response = response;
                        last_response_err = err;
                        callback();
                    });
                },
                // verify the session can no longer be used
                function(callback) {
                    client._activateSession(session1,(err) => {
                        activate_error = err;
                        // BadSessionIdInvalid, BadSessionClosed
                        callback();
                    });
                },

                function(callback) {
                    client.closeSession(session1, true, callback);
                },
                function(callback) {
                    console.log("disconnecting")
                    client.disconnect(callback);
                }
            ], (err) => {
                if (err) {
                    return done(err);
                }
                last_response_err.response.responseHeader.serviceResult.should.eql(StatusCodes.BadSessionNotActivated);
                should.exist(activate_error,
                    "Activate Session should return an error if there has been an attempt to use it before being activated");
                activate_error.message.should.match(/BadSessionIdInvalid|BadSessionClosed/);
                done();
            });
        });

    });
}


	function editComment(comment, cdiv, saveCallback, deleteOnCancel)
	{
		curEdited = {div: cdiv, comment: comment, saveCallback: saveCallback, deleteOnCancel: deleteOnCancel};

		var commentTxt = cdiv.querySelector('.geCommentTxt');
		var actionsDiv = cdiv.querySelector('.geCommentActionsList');

		var textArea = document.createElement('textarea');
		textArea.className = 'geCommentEditTxtArea';
		textArea.style.minHeight = commentTxt.offsetHeight + 'px';
		textArea.value = comment.content;
		cdiv.insertBefore(textArea, commentTxt);

		var btnDiv = document.createElement('div');
		btnDiv.className = 'geCommentEditBtns';

		function reset()
		{
			cdiv.removeChild(textArea);
			cdiv.removeChild(btnDiv);
			actionsDiv.style.display = 'block';
			commentTxt.style.display = 'block';
		};

		var cancelBtn = mxUtils.button(mxResources.get('cancel'), function()
		{
			if (deleteOnCancel)
			{
				cdiv.parentNode.removeChild(cdiv);
				updateNoComments();
			}
			else
			{
				reset();
			}

			curEdited = null;
		});

		cancelBtn.className = 'geCommentEditBtn';
		btnDiv.appendChild(cancelBtn);

		var saveBtn = mxUtils.button(mxResources.get('save'), function()
		{
			commentTxt.innerHTML = '';
			comment.content = textArea.value;
			mxUtils.write(commentTxt, comment.content);
			reset();
			saveCallback(comment);
			curEdited = null;
		});

		// Updates modified state and handles placeholder text
		mxEvent.addListener(textArea, 'keydown', mxUtils.bind(this, function(evt)
		{
			if (!mxEvent.isConsumed(evt))
			{
				if ((mxEvent.isControlDown(evt) || (mxClient.IS_MAC &&
					mxEvent.isMetaDown(evt))) && evt.keyCode == 13 /* Ctrl+Enter */)
				{
					saveBtn.click();
					mxEvent.consume(evt);
				}
				else if (evt.keyCode == 27 /* Escape */)
				{
					cancelBtn.click();
					mxEvent.consume(evt);
				}
			}
		}));

		// Focused to include in viewport before focusin textbox
		saveBtn.focus();
		saveBtn.className = 'geCommentEditBtn gePrimaryBtn';
		btnDiv.appendChild(saveBtn);

		cdiv.insertBefore(btnDiv, commentTxt);
		actionsDiv.style.display = 'none';
		commentTxt.style.display = 'none';
		textArea.focus();
	};