text:
namespace grpc_event_engine {
namespace posix_engine {

class Scheduler {
 public:
  virtual void Run(experimental::EventEngine::Closure* closure) = 0;
  virtual ~Scheduler() = default;
};

class EventHandle {
 public:
  virtual int WrappedFd() = 0;
  // Delete the handle and optionally close the underlying file descriptor if
  // release_fd != nullptr. The on_done closure is scheduled to be invoked
  // after the operation is complete. After this operation, NotifyXXX and SetXXX
  // operations cannot be performed on the handle.
  virtual void OrphanHandle(IomgrEngineClosure* on_done, int* release_fd,
                            absl::string_view reason) = 0;
  // Shutdown a handle. After this operation, NotifyXXX and SetXXX operations
  // cannot be performed.
  virtual void ShutdownHandle(absl::Status why) = 0;
  // Schedule on_read to be invoked when the underlying file descriptor
  // becomes readable.
  virtual void NotifyOnRead(IomgrEngineClosure* on_read) = 0;
  // Schedule on_write to be invoked when the underlying file descriptor
  // becomes writable.
  virtual void NotifyOnWrite(IomgrEngineClosure* on_write) = 0;
  // Schedule on_error to be invoked when the underlying file descriptor
  // encounters errors.
  virtual void NotifyOnError(IomgrEngineClosure* on_error) = 0;
  // Force set a readable event on the underlying file descriptor.
  virtual void SetReadable() = 0;
  // Force set a writable event on the underlying file descriptor.
  virtual void SetWritable() = 0;
  // Force set a error event on the underlying file descriptor.
  virtual void SetHasError() = 0;
  // Returns true if the handle has been shutdown.
  virtual bool IsHandleShutdown() = 0;
  // Execute any pending actions that may have been set to a handle after the
  // last invocation of Work(...) function.
  virtual void ExecutePendingActions() = 0;
  virtual ~EventHandle() = default;
};

class EventPoller {
 public:
  // Return an opaque handle to perform actions on the provided file descriptor.
  virtual EventHandle* CreateHandle(int fd, absl::string_view name,
                                    bool track_err) = 0;
  // Shuts down and deletes the poller. It is legal to call this function
  // only when no other poller method is in progress. For instance, it is
  // not safe to call this method, while a thread is blocked on Work(...).
  // A graceful way to terminate the poller could be to:
  // 1. First orphan all created handles.
  // 2. Send a Kick() to the thread executing Work(...) and wait for the
  //    thread to return.
  // 3. Call Shutdown() on the poller.
  virtual void Shutdown() = 0;
  // Poll all the underlying file descriptors for the specified period
  // and return a vector containing a list of handles which have pending
  // events. The calling thread should invoke ExecutePendingActions on each
  // returned handle to take the necessary pending actions. Only one thread
  // may invoke the Work function at any given point in time. The Work(...)
  // method returns an absl Non-OK status if it was Kicked.
  virtual absl::Status Work(grpc_core::Timestamp deadline,
                            std::vector<EventHandle*>& pending_events) = 0;
  // Trigger the thread executing Work(..) to break out as soon as possible.
  // This function is useful in tests. It may also be used to break a thread
  // out of Work(...) before calling Shutdown() on the poller.
  virtual void Kick() = 0;
  virtual ~EventPoller() = default;
};

}  // namespace posix_engine
}  // namespace grpc_event_engine

#endif  // GRPC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_EVENT_POLLER_H


text:
require 'gorillib/utils/nuke_constants'
require 'gorillib/utils/capture_output'

module Gorillib ;               module Test ;       end ; end
module Meta ; module Gorillib ; module Test ; end ; end ; end

shared_context 'model', :model_spec do
  include Gorillib::TestHelpers

  after(:each){ Gorillib::Test.nuke_constants ; Meta::Gorillib::Test.nuke_constants }

  let(:mock_val){ double('mock value') }

  let(:smurf_class) do
    class Gorillib::Test::Smurf
      include Gorillib::Model
      field :name,       String
      field :smurfiness, Integer
      field :weapon,     Symbol
    end
    Gorillib::Test::Smurf
  end
  let(:papa_smurf   ){ smurf_class.receive(:name => 'Papa Smurf', :smurfiness => 9,  :weapon => 'staff') }
  let(:smurfette    ){ smurf_class.receive(:name => 'Smurfette',  :smurfiness => 11, :weapon => 'charm') }

  let(:smurf_collection_class) do
    smurf_class
    class Gorillib::Test::SmurfCollection < Gorillib::ModelCollection
      include Gorillib::Collection::ItemsBelongTo
      self.item_type        = Gorillib::Test::Smurf
      self.parentage_method = :village
    end
    Gorillib::Test::SmurfCollection
  end

  let(:smurf_village_class) do
    smurf_class ; smurf_collection_class
    module Gorillib::Test
      class SmurfVillage
        include Gorillib::Model
        field      :name,   Symbol
        collection :smurfs, SmurfCollection, item_type: Smurf, key_method: :name
      end
    end
    Gorillib::Test::SmurfVillage
  end

  let(:smurfhouse_class) do
    module Gorillib::Test
      class Smurfhouse
        include Gorillib::Model
        field   :shape, Symbol
        field   :color, Symbol
      end
    end
    Gorillib::Test::Smurfhouse
  end

end

shared_context 'builder', :model_spec, :builder_spec do
  let(:engine_class) do
    class Gorillib::Test::Engine
      include Gorillib::Builder
      magic    :name,         Symbol, :default => ->{ "#{owner? ? owner.name : ''} engine"}
      magic    :carburetor,   Symbol, :default => :stock
      magic    :volume,       Integer, :doc => 'displacement volume, in in^3'
      magic    :cylinders,    Integer
      member   :owner,        Whatever
      self
    end
    Gorillib::Test::Engine
  end

  let(:car_class) do
    engine_class
    class Gorillib::Test::Car
      include Gorillib::Builder
      magic    :name,          Symbol
      magic    :make_model,    String
      magic    :year,          Integer
      magic    :doors,         Integer
      member   :engine,        Gorillib::Test::Engine
      self
    end
    Gorillib::Test::Car
  end

  let(:garage_class) do
    car_class
    class Gorillib::Test::Garage
      include Gorillib::Builder
      collection :cars,       Gorillib::Test::Car, key_method: :name
      self
    end
    Gorillib::Test::Garage
  end

  let(:wildcat) do
    car_class.receive( :name => :wildcat,
      :make_model => 'Buick Wildcat', :year => 1968, :doors => 2,
      :engine => { :volume => 455, :cylinders => 8 } )
  end
  let(:ford_39) do
    car_class.receive( :name => :ford_39,
      :make_model => 'Ford Tudor Sedan', :year => 1939, :doors => 2, )
  end
  let(:garage) do
    garage_class.new
  end
  let(:example_engine) do
    engine_class.new( :name => 'Geo Metro 1.0L', :volume => 61, :cylinders => 3 )
  end

end

redpajama_set_name: RedPajamaGithub


text:
REGISTER_LABELING_WITH_EQUIVALENCES_SOLVERS(BRTS);
REGISTER_LABELING_WITH_EQUIVALENCES_SOLVERS(BRTS_XZ);


text:
/*! `haxe` grammar compiled for Highlight.js 11.4.0 */
(()=>{var e=(()=>{"use strict";return e=>({name:"Haxe",aliases:["hx"],keywords:{
keyword:"break case cast catch continue default do dynamic else enum extern for function here if import in inline never new override package private get set public return static super switch this throw trace try typedef untyped using var while Int Float String Bool Dynamic Void Array ",
built_in:"trace this",literal:"true false null _"},contains:[{
className:"string",begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE,{
className:"subst",begin:"\\$\\{",end:"\\}"},{className:"subst",begin:"\\$",
end:/\W\}/}]
},e.QUOTE_STRING_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,{
className:"meta",begin:"@:",end:"$"},{className:"meta",begin:"#",end:"$",
keywords:{keyword:"if else elseif end error"}},{className:"type",
begin:":[ \t]*",end:"[^A-Za-z0-9_ \t\\->]",excludeBegin:!0,excludeEnd:!0,
relevance:0},{className:"type",begin:":[ \t]*",end:"\\W",excludeBegin:!0,
excludeEnd:!0},{className:"type",begin:"new *",end:"\\W",excludeBegin:!0,
excludeEnd:!0},{className:"class",beginKeywords:"enum",end:"\\{",
contains:[e.TITLE_MODE]},{className:"class",beginKeywords:"abstract",
end:"[\\{$]",contains:[{className:"type",begin:"\\(",end:"\\)",excludeBegin:!0,
excludeEnd:!0},{className:"type",begin:"from +",end:"\\W",excludeBegin:!0,
excludeEnd:!0},{className:"type",begin:"to +",end:"\\W",excludeBegin:!0,
excludeEnd:!0},e.TITLE_MODE],keywords:{keyword:"abstract from to"}},{
className:"class",begin:"\\b(class|interface) +",end:"[\\{$]",excludeEnd:!0,
keywords:"class interface",contains:[{className:"keyword",
begin:"\\b(extends|implements) +",keywords:"extends implements",contains:[{
className:"type",begin:e.IDENT_RE,relevance:0}]},e.TITLE_MODE]},{
className:"function",beginKeywords:"function",end:"\\(",excludeEnd:!0,
illegal:"\\S",contains:[e.TITLE_MODE]}],illegal:/<\//})})()
;hljs.registerLanguage("haxe",e)})();


text:
Views.ipad.news.index = function(win, posts) {
	var view = Ti.UI.createView({
		backgroundColor: "transparent"
	});

	var createTableViewRow = function(post) {

		var avatar_bg = Ti.UI.createView({
			backgroundImage:"images/footer/NCR_iPad_avatar_underlay.png",
			height:66,
			width:63,
			left:0,
			bottom:30
		});

		var avatar = Ti.UI.createImageView({
			image: post.profile_image_url,
			height:50,
			width:50,
			bottom:11
		});

		avatar_bg.add(avatar);

		var body_bg = Ti.UI.createView({
			backgroundImage:"images/footer/NCR_iPad2_feed_quote_box_left.png",
			height:90,
			width:360,
			right:0,
			bottom:20
		});

		var body = Ti.UI.createLabel({
			text:post.text,
			font:{fontFamily:'Helvetica',fontSize:"13dp",fontWeight:'regular'},
			color:"#6c7881",
			width:300,
			left:40,
		});

		body_bg.add(body);

		var time = Ti.UI.createLabel({
			text:Date.parse(post.created_at).toString('M/d/yy h:mm tt'),
			font:{fontFamily:'Helvetica',fontSize:"12dp",fontWeight:'regular'},
			color:"#6c7881",
			bottom:10,
			left:0,
			height:"auto",
			width:"auto"
		});

		var row = Ti.UI.createTableViewRow({
			height:110,
			className:'news'
		});

		row.add(avatar_bg);
		row.add(body_bg);
		row.add(time);

		return row;
	}

	var tableView = Ti.UI.createTableView({
		data:map(createTableViewRow, posts),
		backgroundColor:"transparent",
		width:'100%',
		left:10,
		height:'100%',
		top:10
	});

	view.add(tableView);
	win.add(view);
}


text:
<?php

namespace Victoire\Widget\PollBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Victoire\Widget\PollBundle\Entity\Radio;
use Victoire\Widget\PollBundle\Form\Answer\RadioAnswerType;
use Victoire\Widget\PollBundle\Form\Question\ProposalType;

class QuestionRadioType extends QuestionType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add("proposals", CollectionType::class, [
            "entry_type" => ProposalType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
            'vic_widget_add_btn' => null
        ]);
    }

    public function getQuestionClass()
    {
        return Radio::class;
    }

    public function getAnswerType()
    {
        return RadioAnswerType::class;
    }

    public function getQuestionFormTemplate()
    {
        return "radio";
    }
}


text:
package com.lily.animation;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see <boot_page_img_circle href="http://d.android.com/tools/testing">Testing documentation</boot_page_img_circle>
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
package com.cbooy.cakes.ssm.mybatis.conf;

import com.cbooy.cakes.ssm.mybatis.pojo.UserInfo;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.testng.annotations.Test;

/**
 * mybatis-config.xml配置学习
 *
 * @author haoc
 */
public class App {

  /**
   * demo1,基于配置文件方式
   */
  @Test
  public void testNormal() throws IOException {
    // 1.获取SqlSessionFactory
    String resource = "mybatis/conf/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2.从SqlSessionFactory中拿出SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 3.基于SqlSession获取Mapper操作接口
    IUserInfoMapper userInfoMapper = sqlSession.getMapper(IUserInfoMapper.class);

    // 4.基于接口操作,查询数据库
    UserInfo userInfo = userInfoMapper.getUserInfoById(2);

    System.out.println("get by id userInfo = " + userInfo);

    // 5.关闭SqlSession
    sqlSession.close();
  }

  /**
   * demo2,基于注解形式
   */
  @Test
  public void testAnnotation() throws IOException {
    // 1.获取SqlSessionFactory
    String resource = "mybatis/conf/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    // 2.从SqlSessionFactory中拿出SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 3.基于SqlSession获取Mapper操作接口
    IUserInfoMapperAnnotation userInfoMapper = sqlSession
        .getMapper(IUserInfoMapperAnnotation.class);

    UserInfo userInfo = userInfoMapper.getUserInfoById(3);

    System.out.println("get by id userInfo = " + userInfo);

    // 5.关闭SqlSession
    sqlSession.close();
  }
}


text:
//===============================================================================
// © 2015 eWorkplace Apps.  ALL rights reserved.
// Main Author: Shrey Sharma
// Original DATE: 4/28/2015
//===============================================================================
package com.eworkplaceapps.platform.dbsync;

import com.eworkplaceapps.platform.exception.EwpException;
import com.eworkplaceapps.platform.utils.Utils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * This is a data class for sync reply generated after processing a sync request.
 * The SyncReply will be processed by the request sender to update its
 * sync log, and to resolve any conflicts generated during syncing.
 */
public class SyncReply {

    // The request id sent in SyncRequest
    private String requestId = "";

    // The deviced id of the node that processed the syncing. (Receiver of SyncRequest)
    private String myDeviceId = "";

    private int lastSyncRowNumber = 0;

    // SyncRequest processing status and status message
    private int status = 0;
    private String message = "";

    // The SyncTime bounds within which the syncing was processed.
    // In case of error, this may be shorter than the bounds sent by the requester.
    // In case of no error, it should be the same as the requester's bounds.
    private Date afterSyncTime = new Date();
    private Date toSyncTime = new Date();

    // A flag to indicate if it was partial syncing. (In case of error.)
    private boolean partialSync = false;

    // The list of conflicts generated during syncing, in the order of timestamp.
    private List<SyncConflict> conflictList = new ArrayList<SyncConflict>();

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public String getMyDeviceId() {
        return myDeviceId;
    }

    public void setMyDeviceId(String myDeviceId) {
        this.myDeviceId = myDeviceId;
    }

    public int getLastSyncRowNumber() {
        return lastSyncRowNumber;
    }

    public void setLastSyncRowNumber(int lastSyncRowNumber) {
        this.lastSyncRowNumber = lastSyncRowNumber;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getAfterSyncTime() {
        return afterSyncTime;
    }

    public void setAfterSyncTime(Date afterSyncTime) {
        this.afterSyncTime = afterSyncTime;
    }

    public Date getToSyncTime() {
        return toSyncTime;
    }

    public void setToSyncTime(Date toSyncTime) {
        this.toSyncTime = toSyncTime;
    }

    public boolean isPartialSync() {
        return partialSync;
    }

    public void setPartialSync(boolean partialSync) {
        this.partialSync = partialSync;
    }

    public List<SyncConflict> getConflictList() {
        return conflictList;
    }

    public void setConflictList(List<SyncConflict> conflictList) {
        this.conflictList = conflictList;
    }

    /* XML:

    <RemoteSyncReply>
        <RequestId></RequestId>
        <MyDeviceId></MyDeviceId>
        <Status></Status>
        <Message></Message>
        <FromSyncTime></FromSyncTime>
        <ToSyncTime></ToSyncTime>
        <PartialSync></PartialSync>
        <SyncConflictList>
        ...
        </SyncConflictList>
    </RemoteSyncReply>
    */

    /**
     * SYNC Reply xml
     *
     * @param xmlSerializer
     * @param syncReply
     * @throws IOException
     */
    public static void toXmlWriter(XmlSerializer xmlSerializer, SyncReply syncReply) throws IOException {
        // Start Root tag
        xmlSerializer.startTag("", "RemoteSyncReply");
        xmlSerializer.startTag("", "RequestId");
        xmlSerializer.text(syncReply.getRequestId());
        xmlSerializer.endTag("", "RequestId");
        xmlSerializer.startTag("", "MyDeviceId");
        xmlSerializer.text(syncReply.getMyDeviceId());
        xmlSerializer.endTag("", "MyDeviceId");
        xmlSerializer.startTag("", "Status");
        xmlSerializer.text(syncReply.getStatus() + "");
        xmlSerializer.endTag("", "Status");
        xmlSerializer.startTag("", "Message");
        xmlSerializer.text(syncReply.getMessage());
        xmlSerializer.endTag("", "Message");
        xmlSerializer.startTag("", "AfterSyncTime");
        String s = Utils.dateAsStringWithoutUTC(syncReply.getAfterSyncTime());
        xmlSerializer.text(s);
        xmlSerializer.endTag("", "AfterSyncTime");
        xmlSerializer.startTag("", "ToSyncTime");
        String k = Utils.dateAsStringWithoutUTC(syncReply.getToSyncTime());
        xmlSerializer.text(k);
        xmlSerializer.endTag("", "ToSyncTime");
        xmlSerializer.startTag("", "PartialSync");
        xmlSerializer.text(syncReply.isPartialSync() + "");
        xmlSerializer.endTag("", "PartialSync");
        SyncConflict.listToXmlWriter(syncReply.conflictList, xmlSerializer);
        xmlSerializer.endTag("", "RemoteSyncReply");
    }

    public static SyncReply parseXml(XmlPullParser object) throws EwpException {
        try {

            int event = object.getEventType();
            String text = null;
            SyncReply syncReply = null;
            SyncConflict syncConflict = null;
            while (event != XmlPullParser.END_DOCUMENT) {
                String name = object.getName();
                switch (event) {
                    case XmlPullParser.START_TAG:
                        if ("RemoteSyncReply".equals(name)) {
                            syncReply = new SyncReply();
                        }
                        if ("SyncConflict".equals(name)) {
                            syncConflict = new SyncConflict();
                            syncReply.getConflictList().add(syncConflict);
                        }
                        break;
                    case XmlPullParser.TEXT:
                        text = object.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if ("RequestId".equals(name)) {
                            syncReply.setRequestId(text);
                        } else if ("MyDeviceId".equals(name)) {
                            syncReply.setMyDeviceId(text);
                        } else if ("Status".equals(name)) {
                            syncReply.setStatus(Integer.parseInt(text));
                        } else if ("Message".equals(name)) {
                            syncReply.setMessage(text);
                        } else if ("AfterSyncTime".equals(name)) {
                            syncReply.setAfterSyncTime(Utils.dateFromString(text, true, true));
                        } else if ("ToSyncTime".equals(name)) {
                            syncReply.setToSyncTime(Utils.dateFromString(text, true, true));
                        } else if ("PartialSync".equals(name)) {
                            syncReply.setPartialSync("true".equals(text) || "True".equals(text));
                        } else if ("ConflictType".equals(name)) {
                            syncConflict.conflictType = SyncConflict.SyncConflictType.toSyncConflictType(text);
                        } else if ("DeviceId".equals(name)) {
                            syncConflict.originalSyncOp.setDeviceId(text);
                        } else if ("TableName".equals(name)) {
                            syncConflict.originalSyncOp.setTableName(text);
                        } else if ("PKName".equals(name)) {
                            syncConflict.originalSyncOp.setPkName(text);
                        }else if ("PKValue".equals(name)) {
                            syncConflict.originalSyncOp.setPkValue(text);
                        }
                        else if ("OpType".equals(name)) {
                            syncConflict.originalSyncOp.setOpType(text);
                        } else if ("ColumnValue".equals(name)) {
                            syncConflict.originalSyncOp.getColumnValues().put(object.getAttributeValue(null, "Name"), object.getAttributeValue(null, "Value"));
                        } else if ("SyncTransactionId".equals(name)) {
                            syncConflict.originalSyncOp.setSyncTransactionId(text);
                        } else if ("CreatedTime".equals(name)) {
                            syncConflict.originalSyncOp.setCreatedTime(Utils.dateFromString(text, true, true));
                        }
                        break;
                    default:
                        break;
                }
                event = object.next();
            }
            return syncReply;
        } catch (XmlPullParserException e) {
            EwpException ex = new EwpException(e);
            throw ex;
        } catch (IOException e) {
            EwpException ex = new EwpException(e);
            throw ex;
        }
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\simpletest\Tests\BrowserTest.
 */

namespace Drupal\simpletest\Tests;

use Drupal\simpletest\WebTestBase;

/**
 * Tests the internal browser of the testing framework.
 *
 * @group simpletest
 */
class BrowserTest extends WebTestBase {

  /**
   * A flag indicating whether a cookie has been set in a test.
   *
   * @var bool
   */
  protected static $cookieSet = FALSE;

  /**
   * Modules to enable.
   *
   * @var string[]
   */
  public static $modules = ['block'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->drupalPlaceBlock('local_tasks_block');
  }

  /**
   * Test \Drupal\simpletest\WebTestBase::getAbsoluteUrl().
   */
  function testGetAbsoluteUrl() {
    $url = 'user/login';

    $this->drupalGet($url);
    $absolute = \Drupal::url('user.login', array(), array('absolute' => TRUE));
    $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
    $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');

    $this->drupalPostForm(NULL, array(), t('Log in'));
    $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
    $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');

    $this->clickLink('Create new account');
    $absolute = \Drupal::url('user.register', array(), array('absolute' => TRUE));
    $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
    $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
  }

  /**
   * Tests XPath escaping.
   */
  function testXPathEscaping() {
    $testpage = <<< EOF

A "weird" link, just to bother the dumb "XPath 1.0"
A second "even more weird" link, in memory of George O'Malley
A \$third$ link, so weird it's worth $1 million
A fourth link, containing alternative \\1 regex backreferences \\2

EOF;
    $this->setRawContent($testpage);

    // Matches the first link.
    $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A "weird" link, just to bother the dumb "XPath 1.0"'));
    $this->assertEqual($urls[0]['href'], 'link1', 'Match with quotes.');

    $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A second "even more weird" link, in memory of George O\'Malley'));
    $this->assertEqual($urls[0]['href'], 'link2', 'Match with mixed single and double quotes.');

    $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A $third$ link, so weird it\'s worth $1 million'));
    $this->assertEqual($urls[0]['href'], 'link3', 'Match with a regular expression back reference symbol (dollar sign).');

    $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A fourth link, containing alternative \\1 regex backreferences \\2'));
    $this->assertEqual($urls[0]['href'], 'link4', 'Match with another regular expression back reference symbol (double backslash).');
  }

  /**
   * Tests that cookies set during a request are available for testing.
   */
  public function testCookies() {
    // Check that the $this->cookies property is populated when a user logs in.
    $user = $this->drupalCreateUser();
    $edit = ['name' => $user->getUsername(), 'pass' => $user->pass_raw];
    $this->drupalPostForm('<front>', $edit, t('Log in'));
    $this->assertEqual(count($this->cookies), 1, 'A cookie is set when the user logs in.');

    // Check that the name and value of the cookie match the request data.
    $cookie_header = $this->drupalGetHeader('set-cookie', TRUE);

    // The name and value are located at the start of the string, separated by
    // an equals sign and ending in a semicolon.
    preg_match('/^([^=]+)=([^;]+)/', $cookie_header, $matches);
    $name = $matches[1];
    $value = $matches[2];

    $this->assertTrue(array_key_exists($name, $this->cookies), 'The cookie name is correct.');
    $this->assertEqual($value, $this->cookies[$name]['value'], 'The cookie value is correct.');

    // Set a flag indicating that a cookie has been set in this test.
    // @see testCookieDoesNotBleed()
    static::$cookieSet = TRUE;
  }

  /**
   * Tests that the cookies from a previous test do not bleed into a new test.
   *
   * @see static::testCookies()
   */
  public function testCookieDoesNotBleed() {
    // In order for this test to be effective it should always run after the
    // testCookies() test.
    $this->assertTrue(static::$cookieSet, 'Tests have been executed in the expected order.');
    $this->assertEqual(count($this->cookies), 0, 'No cookies are present at the start of a new test.');
  }

}


text:
package org.zalando.nakadi.service.subscription.zk;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundPathAndBytesable;
import org.apache.curator.framework.api.DeleteBuilder;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.curator.framework.api.SetDataBuilder;
import org.apache.curator.framework.api.WatchPathable;
import org.apache.zookeeper.KeeperException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.zalando.nakadi.domain.EventTypePartition;
import org.zalando.nakadi.repository.zookeeper.CuratorFrameworkRotator;
import org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder;
import org.zalando.nakadi.service.subscription.model.Partition;
import org.zalando.nakadi.service.subscription.model.Session;

import java.util.Collections;

public class NewZkSubscriptionClientTest {

    private final CuratorFramework curator = Mockito.mock(CuratorFramework.class);
    private final CuratorFrameworkRotator curatorFrameworkRotator = Mockito.mock(CuratorFrameworkRotator.class);
    private final GetDataBuilder getDataBuilder = Mockito.mock(GetDataBuilder.class);
    private final SetDataBuilder setDataBuilder = Mockito.mock(SetDataBuilder.class);
    private final BackgroundPathAndBytesable bytesable = Mockito.mock(BackgroundPathAndBytesable.class);
    private final WatchPathable watchPathable = Mockito.mock(WatchPathable.class);
    private final DeleteBuilder deleteBuilder = Mockito.mock(DeleteBuilder.class);

    private final ObjectMapper objectMapper = new ObjectMapper();
    private NewZkSubscriptionClient client;
    private byte[] topology;

    @Before
    public void setUp() throws JsonProcessingException {
        Mockito.when(curatorFrameworkRotator.takeCuratorFramework()).thenReturn(curator);
        Mockito.when(curator.getData()).thenReturn(getDataBuilder);
        Mockito.when(curator.setData()).thenReturn(setDataBuilder);
        Mockito.when(setDataBuilder.withVersion(Mockito.anyInt())).thenReturn(bytesable);
        Mockito.when(getDataBuilder.storingStatIn(Mockito.any())).thenReturn(watchPathable);
        Mockito.when(curator.delete()).thenReturn(deleteBuilder);

        topology = objectMapper.writeValueAsBytes(new ZkSubscriptionClient.Topology(
                new Partition[]{new Partition(
                        "test-event-type", "0", "session-id-xxx", null, Partition.State.REASSIGNING)},
                null
        ));
        client = new NewZkSubscriptionClient(
                "subscription-id-xxx",
                new ZooKeeperHolder.RotatingCuratorFramework(curatorFrameworkRotator),
                objectMapper
        );
    }

    @Test(expected = SubscriptionNotInitializedException.class)
    public void testNoTopologyNodeThenSubscriptionIsNotInited() throws Exception {
        Mockito.when(curator.getData().storingStatIn(Mockito.any()).forPath(Mockito.any()))
                .thenThrow(KeeperException.NoNodeException.class);

        client.transfer("session-id-xxx", null);
    }

    @Test
    public void testTopologyUpdated() throws Exception {
        Mockito.when(curator.getData().storingStatIn(Mockito.any()).forPath(Mockito.any()))
                .thenReturn(topology);
        Mockito.when(curator.getData().forPath(Mockito.any()))
                .thenReturn(topology);
        Mockito.when(curator.setData().withVersion(Mockito.anyInt()).forPath(Mockito.any()))
                .thenReturn(null);

        client.transfer("session-id-xxx", Collections.singleton(
                new EventTypePartition("test-event-type", "0")));
        Mockito.verify(bytesable).forPath(Mockito.anyString(), Mockito.any());
        Mockito.reset(bytesable);
    }

    @Test
    public void testTopologyWasNotUpdated() throws Exception {
        Mockito.when(curator.getData().storingStatIn(Mockito.any()).forPath(Mockito.any()))
                .thenReturn(topology);
        Mockito.when(curator.getData().forPath(Mockito.any()))
                .thenReturn(topology);
        Mockito.when(curator.setData().withVersion(Mockito.anyInt()).forPath(Mockito.any()))
                .thenReturn(null);

        client.transfer("session-id-ANOTHER", Collections.singleton(
                new EventTypePartition("test-event-type", "0")));
        Mockito.verify(bytesable, Mockito.times(0)).forPath(Mockito.anyString(), Mockito.any());
        Mockito.reset(bytesable);
    }

    @Test
    public void whenUnregisterSessionMissingNodeThenOk() throws Exception {

        Mockito.when(curator.delete().forPath(Mockito.any()))
                .thenThrow(KeeperException.NoNodeException.class);

        final Session session = Session.generate(1, ImmutableList.of());

        // It should not throw.
        client.unregisterSession(session);
    }
}


text:
{% extends 'auth/admin/base.html' %}
{% block content %}

{% if added %}

You've been added to {{admin_group}} group.

Once this change propagates (~1 min) you should be able to access
Auth Admin UI and other protected pages.

Meanwhile, you can configure OAuth2 client ID used by the web UI by visiting
OAuth client ID configuration page.

{% else %}

You are already a member of {{admin_group}} group.

You should be able to access Auth Admin UI and other
protected pages. It takes up to 1 min for recent changes to propagate, be
patient.

If you are looking for how to configure OAuth2 client ID used by the web UI,
visit OAuth client ID configuration page.

{% endif %}
{% if return_url %}

Go back to {{return_url}}.

{% endif %}

{% endblock %}


text:
title: "Salesforce"
linkTitle: "Salesforce"
quote: "It felt like it could be the next Kubernetes, for service mesh."
author:
    name: "Pratima Nambiar"
    image: "/img/authors/pratima-nambiar.jpg"
companyName: "Salesforce"
companyURL: "https://www.salesforce.com/"
logo: "/logos/salesforce.svg"
skip_toc: true
skip_byline: true
skip_pagenav: true
skip_feedback: true
doc_type: article
sidebar_force: sidebar_case_study
type: case-studies
weight: 40
---

Istio and Envoy are foundational building blocks of the Salesforce Service Mesh. In [a presentation at IstioCon 2021](https://events.istio.io/istiocon-2021/sessions/salesforce-service-mesh--our-istio-journey/), Pratima Nambiar walks through Salesforce's service mesh journey. She briefly talks about why they chose the service mesh design pattern, how they initially built it using Envoy and an in-house control plane, and their subsequent pivot to Istio. She discusses how they are currently leveraging Istio and their plan to increase adoption of Istio to further enhance their Service Mesh platform.

<iframe width="696" height="392" src="https://www.youtube-nocookie.com/embed/upYyX0E6Wwk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

[Download the slides](https://events.istio.io/istiocon-2021/slides/f2s-SalesforceServiceMesh-PratimaNambiar.pdf)


text:
#ifndef __PERF_STRFILTER_H
#define __PERF_STRFILTER_H
/* General purpose glob matching filter */

/* ANDROID_CHANGE_BEGIN */
#if 0
#include <linux/list.h>
#else
#include "util/include/linux/list.h"
#endif
/* ANDROID_CHANGE_END */
#include <stdbool.h>

/* A node of string filter */
struct strfilter_node {
	struct strfilter_node *l;	/* Tree left branche (for &,|) */
	struct strfilter_node *r;	/* Tree right branche (for !,&,|) */
	const char *p;		/* Operator or rule */
};

/* String filter */
struct strfilter {
	struct strfilter_node *root;
};

/**
 * strfilter__new - Create a new string filter
 * @rules: Filter rule, which is a combination of glob expressions.
 * @err: Pointer which points an error detected on @rules
 *
 * Parse @rules and return new strfilter. Return NULL if an error detected.
 * In that case, *@err will indicate where it is detected, and *@err is NULL
 * if a memory allocation is failed.
 */
struct strfilter *strfilter__new(const char *rules, const char **err);

/**
 * strfilter__compare - compare given string and a string filter
 * @self: String filter
 * @str: target string
 *
 * Compare @str and @self. Return true if the str match the rule
 */
bool strfilter__compare(struct strfilter *self, const char *str);

/**
 * strfilter__delete - delete a string filter
 * @self: String filter to delete
 *
 * Delete @self.
 */
void strfilter__delete(struct strfilter *self);

#endif


text: {{+partials.standard_extensions_api api:apis.declarative_content intro:intros.declarativeContent}}


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/InfoDisplayListener.java,v $
// $RCSfile: InfoDisplayListener.java,v $
// $Revision: 1.4 $
// $Date: 2004/10/14 18:05:44 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.event;

/**
 * Listens for requests to display information.
 */
public interface InfoDisplayListener extends java.util.EventListener {

    /**
     * Request to have a URL displayed in a Browser.
     *
     * @param event InfoDisplayEvent
     */
    public void requestURL(InfoDisplayEvent event);

    /**
     * Request to have a message displayed in a dialog window.
     *
     * @param event InfoDisplayEvent
     */
    public void requestMessage(InfoDisplayEvent event);

    /**
     * Request to have an information line displayed in an application
     * status window.
     *
     * @param event InfoDisplayEvent
     */
    public void requestInfoLine(InfoDisplayEvent event);

    /**
     * Request that plain text or html text be displayed in a browser.
     *
     * @param event InfoDisplayEvent
     */
    public void requestBrowserContent(InfoDisplayEvent event);

    /**
     * Request that the MapBean cursor be set to a certain type.
     *
     * @param cursor java.awt.Cursor to set over the MapBean.
     */
    public void requestCursor(java.awt.Cursor cursor);

    /**
     * Request a tool tip be shown.
     *
     * @param event The InfoDisplayEvent containing the text and
     *        requestor.
     */
    public void requestShowToolTip(InfoDisplayEvent event);

    /**
     * Request a tool tip be hidden.
     */
    public void requestHideToolTip();

}


text:
class SlickdealsCli::CLI

	def call
		build_popular
		woot_deals
		welcome
		user_choice
		goodbye
	end

	def welcome
		puts "***************************************"
		puts "Welcome to your Slickdeals of the day!!"
		puts "***************************************"
		puts "What type of deals would you like to see?"
	end

	def user_choice
		input = nil
		while input != "exit"
			puts "Type 1 for today's Popular Deals or 2 for the Deal of the day from Woot or exit:"
			input = gets.strip.downcase
			if input.to_i == 1
				popular_deals_list
			elsif input.to_i == 2
				woot_deal = @deals[input.to_i-1]
				puts "Here is the Daily Deal from Woot!"
				puts "#{woot_deal.name}:".colorize(:light_blue) + " #{woot_deal.price}.".colorize(:green)
				puts "You can find this deal at #{woot_deal.url}".colorize(:blue)
			else
				puts "Hmm, I'm not familiar with that input"
			end
		end
	end

	def goodbye
		puts "Come back tomorrow for more deals! Have a nice day!"
	end

	private

	def build_popular
		pop_slick = SlickdealsCli::Deal.scrape_popular_slickdeals
		@pop_deals = SlickdealsCli::Popular.create_popular_deal(pop_slick)
	end

	def popular_deals_list
		puts "Here are the current Popular Deals on Slickdeals!!"
		SlickdealsCli::Popular.all.each.with_index(1) do |deal, index|
			puts "#{index}: ".colorize(:red) + "#{deal.name}".colorize(:light_blue)
			puts "You can find the deal at: "
			puts "#{deal.url}"
			puts "The seller is #{deal.seller}.".colorize(:blue)
			puts ""
		end
	end

	def woot_deals
		@deals = SlickdealsCli::Deal.feature
	end

end


text:
@implementation YWHomeFestivalTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.BGView.layer.borderWidth = 2.f;
    self.BGView.layer.borderColor = [UIColor colorWithHexString:@"#6d6f6e"].CGColor;
    self.BGView.layer.cornerRadius = 5.f;
    self.BGView.layer.masksToBounds = YES;

    self.boardLabel.layer.borderWidth = 2.f;
    self.boardLabel.layer.cornerRadius = 19.f;
    self.boardLabel.layer.masksToBounds = YES;
    self.statusLabel.transform = CGAffineTransformRotate(self.statusLabel.transform, -M_1_PI);
    [self statusShow];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)setStatus:(NSInteger)status{
    if (_status == status) return;
    _status = status;
    [self statusShow];
}

- (void)statusShow{
    self.boardLabel.layer.borderColor = [UIColor colorWithHexString:self.status == 1?@"#3cbaea":(self.status == 2?@"#FF0000":@"#b3b3b3")].CGColor;
    self.statusLabel.textColor = [UIColor colorWithHexString:self.status == 1?@"#3cbaea":(self.status == 2?@"#FF0000":@"#b3b3b3")];
    self.statusLabel.text = self.status == 1?@"未开始":(self.status == 2?@"进行中":@"已结束");
}

- (void)setModel:(YWHomeFestivalModel *)model{
    if (!model)return;
    _model = model;
    [self dataSet];
}
- (void)dataSet{
    NSString * showName;
    NSInteger cut = (int)[self.model.rebate floatValue]*100;
    if (cut%10 == 0) {
        showName = cut== 100?@"全付":[NSString stringWithFormat:@"%zi折",(cut/10)];
    }else{
        showName = [NSString stringWithFormat:@"%zi折",cut];
    }

    self.nameLabel.text = [NSString stringWithFormat:@"%@ 全场%@",self.model.title,showName];
    self.timeLabel.text = [NSString stringWithFormat:@"%@~%@",[JWTools dateWithYearMonthDayStr:self.model.btime],[JWTools dateWithYearMonthDayStr:self.model.etime]];;
}

@end


text:
package cl.uchile.dcc.cc5604.proyectos.priceComparator;

import javax.ejb.Local;

@Local
public interface ListsManagerLocal extends IListManager {
}


text:
package exceptions;

/**
 * EXCEPTION for data that is too much to display
 *
 * @author Florian Thiery M.Sc.
 * @author i3mainz - Institute for Spatial Information and Surveying Technology
 * @version 11.06.2015
 */
public class MemoryException extends Exception {

	/**
	 * EXCEPTION for Config functions
	 * @param message
	 */
	public MemoryException(String message) {
        super(message);
    }

	/**
	 * EXCEPTION for Config functions
	 */
	public MemoryException() {
        super();
    }
}


text:
function dg_setup()
% Setup the toolbox dg_setup

root = fileparts(mfilename('fullpath')) ;

run(fullfile(root, 'vlfeat', 'toolbox', 'vl_setup.m')) ;
run(fullfile(root, 'matconvnet', 'matlab', 'vl_setupnn.m')) ;

addpath(fullfile(root, 'core'));
addpath(fullfile(root, 'helpers'));
addpath(fullfile(root, 'layers'));


text:
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 04, 2017 at 02:02 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `hotel_app`
--

-- --------------------------------------------------------

--
-- Table structure for table `apps`
--

CREATE TABLE IF NOT EXISTS `apps` (
`id` int(11) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `owner_id` int(11) NOT NULL,
  `language` varchar(255) DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `apps`
--

INSERT INTO `apps` (`id`, `title`, `owner_id`, `language`) VALUES
(1, 'My Hotel', 5, 'english');

-- --------------------------------------------------------

--
-- Table structure for table `guests`
--

CREATE TABLE IF NOT EXISTS `guests` (
`id` int(11) NOT NULL,
  `app_id` int(11) NOT NULL,
  `room_id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `created_by` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `rooms`
--

CREATE TABLE IF NOT EXISTS `rooms` (
`id` int(11) NOT NULL,
  `app_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `suppliers`
--

CREATE TABLE IF NOT EXISTS `suppliers` (
`id` int(11) NOT NULL,
  `app_id` int(11) NOT NULL,
  `first_name` int(11) DEFAULT NULL,
  `last_name` int(11) DEFAULT NULL,
  `created_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
  `app_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `dob` datetime NOT NULL,
  `join_date` datetime NOT NULL,
  `mobile_no` varchar(255) NOT NULL,
  `emergency_no` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state` varchar(255) NOT NULL,
  `zip_code` varchar(255) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `verified` int(11) NOT NULL DEFAULT '0',
  `active` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `app_id`, `group_id`, `first_name`, `last_name`, `dob`, `join_date`, `mobile_no`, `emergency_no`, `email`, `address`, `city`, `state`, `zip_code`, `username`, `password`, `verified`, `active`) VALUES
(5, 1, 1, 'Administrator', NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '', '', '', '', '', '', '', 'admin', '21232f297a57a5a743894a0e4a801fc3', 1, 0);

-- --------------------------------------------------------

--
-- Table structure for table `user_groups`
--

CREATE TABLE IF NOT EXISTS `user_groups` (
`id` int(11) NOT NULL,
  `app_id` int(11) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `keyword` varchar(255) DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `user_groups`
--

INSERT INTO `user_groups` (`id`, `app_id`, `title`, `keyword`) VALUES
(1, 1, 'Admin', 'admin');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `apps`
--
ALTER TABLE `apps`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `guests`
--
ALTER TABLE `guests`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `rooms`
--
ALTER TABLE `rooms`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `suppliers`
--
ALTER TABLE `suppliers`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `user_groups`
--
ALTER TABLE `user_groups`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `apps`
--
ALTER TABLE `apps`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `guests`
--
ALTER TABLE `guests`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `rooms`
--
ALTER TABLE `rooms`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `suppliers`
--
ALTER TABLE `suppliers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `user_groups`
--
ALTER TABLE `user_groups`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
import log
import mxnet as mx
import numpy as np
from collections import namedtuple
from cv_tools import image_tool

logger = log.get_logger(name='eval', filename='eval.log', filemode='a', level=log.DEBUG, file_and_line=True)

class Eval:

    def __init__(self,
                 modelprefix,
                 imagepath,
                 inputshape,
                 labelpath,
                 epoch=0,
                 format='NCHW'):
        self.modelprefix = modelprefix
        self.imagepath = imagepath
        self.labelpath = labelpath
        self.inputshape = inputshape
        self.epoch = epoch
        self.format = format

        with open(labelpath, 'r') as fo:
            self.labels = [l.rstrip() for l in fo]

        sym, arg_params, aux_params = mx.model.load_checkpoint(self.modelprefix, self.epoch)
        self.mod = mx.mod.Module(symbol=sym, context=mx.gpu(), label_names=None)
        self.mod.bind(for_training=False,
                      data_shapes=[('data', (1, self.inputshape[0], self.inputshape[1], self.inputshape[2]))],
                      label_shapes=self.mod._label_shapes)
        self.mod.set_params(arg_params, aux_params, allow_missing=True)

    def predict(self):
        Batch = namedtuple('Batch', ['data'])

        datas = []
        names = []
        prob_predicts = []
        label_predicts = []

        logger.info('begin to load image')
        for _ in self.imagepath:
            x = image_tool.get_image(_, self.inputshape, format=self.format)
            datas.append(x)
            names.append(_)

        logger.info('begin to predict')
        for _ in datas:
            self.mod.forward(Batch([mx.nd.array(_)]))
            prob = self.mod.get_outputs()[0].asnumpy()

            # print the top-1
            prob = np.squeeze(prob)
            a = np.argsort(prob)[::-1]
            for i in a[0:1]:
                print('probability=%f, class=%s' % (prob[i], self.labels[i]))
                prob_predicts.append(prob[i])
                label_predicts.append(self.labels[i])
        return names, prob_predicts, label_predicts


text:
from __future__ import annotations

import csv
from operator import attrgetter
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Sequence

from airflow.models import BaseOperator
from airflow.providers.google.ads.hooks.ads import GoogleAdsHook
from airflow.providers.google.cloud.hooks.gcs import GCSHook

if TYPE_CHECKING:
    from airflow.utils.context import Context

class GoogleAdsToGcsOperator(BaseOperator):
    """
    Fetches the daily results from the Google Ads API for 1-n clients
    Converts and saves the data as a temporary CSV file
    Uploads the CSV to Google Cloud Storage

    .. seealso::
        For more information on the Google Ads API, take a look at the API docs:
        https://developers.google.com/google-ads/api/docs/start

    .. seealso::
        For more information on how to use this operator, take a look at the guide:
        :ref:`howto/operator:GoogleAdsToGcsOperator`

    :param client_ids: Google Ads client IDs to query
    :param query: Google Ads Query Language API query
    :param attributes: List of Google Ads Row attributes to extract
    :param bucket: The GCS bucket to upload to
    :param obj: GCS path to save the object. Must be the full file path (ex. `path/to/file.txt`)
    :param gcp_conn_id: Airflow Google Cloud connection ID
    :param google_ads_conn_id: Airflow Google Ads connection ID
    :param page_size: The number of results per API page request. Max 10,000
    :param gzip: Option to compress local file or file data for upload
    :param impersonation_chain: Optional service account to impersonate using short-term
        credentials, or chained list of accounts required to get the access_token
        of the last account in the list, which will be impersonated in the request.
        If set as a string, the account must grant the originating account
        the Service Account Token Creator IAM role.
        If set as a sequence, the identities from the list must grant
        Service Account Token Creator IAM role to the directly preceding identity, with first
        account from the list granting this role to the originating account (templated).
    :param api_version: Optional Google Ads API version to use.
    """

    template_fields: Sequence[str] = (
        "client_ids",
        "query",
        "attributes",
        "bucket",
        "obj",
        "impersonation_chain",
    )

    def __init__(
        self,
        *,
        client_ids: list[str],
        query: str,
        attributes: list[str],
        bucket: str,
        obj: str,
        gcp_conn_id: str = "google_cloud_default",
        google_ads_conn_id: str = "google_ads_default",
        page_size: int = 10000,
        gzip: bool = False,
        impersonation_chain: str | Sequence[str] | None = None,
        api_version: str | None = None,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.client_ids = client_ids
        self.query = query
        self.attributes = attributes
        self.bucket = bucket
        self.obj = obj
        self.gcp_conn_id = gcp_conn_id
        self.google_ads_conn_id = google_ads_conn_id
        self.page_size = page_size
        self.gzip = gzip
        self.impersonation_chain = impersonation_chain
        self.api_version = api_version

    def execute(self, context: Context) -> None:
        service = GoogleAdsHook(
            gcp_conn_id=self.gcp_conn_id,
            google_ads_conn_id=self.google_ads_conn_id,
            api_version=self.api_version,
        )
        rows = service.search(client_ids=self.client_ids, query=self.query, page_size=self.page_size)

        try:
            getter = attrgetter(*self.attributes)
            converted_rows = [getter(row) for row in rows]
        except Exception as e:
            self.log.error("An error occurred in converting the Google Ad Rows. \n Error %s", e)
            raise

        with NamedTemporaryFile("w", suffix=".csv") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(converted_rows)
            csvfile.flush()

            hook = GCSHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
            hook.upload(
                bucket_name=self.bucket,
                object_name=self.obj,
                filename=csvfile.name,
                gzip=self.gzip,
            )
            self.log.info("%s uploaded to GCS", self.obj)


text:
<?php
/**
 * @license https://github.com/bitpay/opencart-bitpay/blob/master/LICENSE MIT
 */

class ModelPaymentBitpay extends Model
{

    /**
     * @param string $address
     *
     * @return array
     */
    public function getMethod($address)
    {
        $this->load->language('payment/bitpay');

        if ($this->config->get('bitpay_status'))
        {
            $status = TRUE;
        }
        else
        {
            $status = FALSE;
        }

        $method_data = array();

        if ($status)
        {
            $method_data = array(
                'code'       => 'bitpay',
                'title'      => $this->language->get('text_title'),
                'sort_order' => $this->config->get('bitpay_sort_order'),
            );
        }

        return $method_data;
    }
}


text:
layout: page
title: "ENVD 4340: Landscape Design Studio Statistics"
comments: true
description: "blanks"
keywords: "ENVD,4340,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 9.7%

**Percent incomplete**: 2.56%

**Average grade** (4.0 scale): 3.16

**Standard deviation in grades** (4.0 scale): 0.33

**Average workload** (raw): 5.5

**Standard deviation in workload** (raw): 0.0

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.71

**Standard deviation in course rating** (6 point scale): 0.0

**Average instructor rating** (6 point scale): 6.0

**Standard deviation in instructor rating** (6 point scale): 0.0

**Instructors**: David Kahn, Joni Palmer, Alison Kipp Yager

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2008, Fall 2013, Fall 2015

**Credits**: 6

**RAP/Honors class?** Neither

**Number of Sections**: 3

**Department**: ARPL

**College**: College of Architecture and Planning

**Level**: Upper

**Activity**: LAB - Laboratory


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ges. Naturf. Freunde Berlin Mag. Neuesten Entdeck. Gesammten Naturk. 7:297. 1816

#### Original name
null

### Remarks
null


text:
var config = require("config")
var fs = require('fs')

var exports = module.exports = {}

//just make sure the data directory is there on startup
exports.convert = function(){

	var inputDir = config['Dump']['in']
	var outputDir = config['Dump']['out']

	var files = fs.readdirSync(inputDir)

	for (var x in files){

		var file = files[x]

		var stats = fs.statSync(inputDir + file)

		if (!stats.isDirectory()){

			var path = inputDir + file;

			//there are too many files to do this async on my system
			var data = fs.readFileSync(path, "utf8")

			console.log("("+x+")",path)

			data = JSON.parse(data)

			if (data['entries']){

				for (var aBib in data['entries']){

					var bib = data['entries'][aBib]

					var aline = JSON.stringify(bib)

					fs.appendFileSync(outputDir, aline + "\n");

				}

			}

		}

	}

}

exports.convertItems = function(){

	var inputDir = config['Dump']['in']
	var outputDir = config['Dump']['outItems']

	var files = fs.readdirSync(inputDir)

	var allIds = {}

	for (var x in files){

		var file = files[x]

		var stats = fs.statSync(inputDir + file)

		if (!stats.isDirectory()){

			var path = inputDir + file;

			//there are too many files to do this async on my system
			var data = fs.readFileSync(path, "utf8")

			console.log("("+x+")",path)

			data = JSON.parse(data)

			if (data['entries']){

				for (var aBib in data['entries']){

					var bib = data['entries'][aBib]

					if (!allIds[bib.id]){

						allIds[bib.id] = 1

						var aline = JSON.stringify(bib)
						fs.appendFileSync(outputDir, aline + "\n");

					}else{
						console.log(bib.id)
					}

				}

			}

		}

	}

}


text:
<?php

namespace Indigo\Shorten\Provider;

use Indigo\Shorten\Provider;
use Indigo\Http\Client;

/**
 * Shorten URL with Bit.ly
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class Bitly implements Provider
{
    /**
     * API Endpoint
     */
    const ENDPOINT = 'https://api-ssl.bitly.com/v3';

    /**
     * HTTP Client
     *
     * @var Client
     */
    protected $client;

    /**
     * @var string
     */
    protected $apiKey;

    /**
     * @param Client $client
     * @param string $apiKey
     */
    public function __construct(Client $client, $apiKey = null)
    {
        $this->client = $client;
        $this->apiKey = $apiKey;
    }

    /**
     * {@inheritdoc}
     */
    public function shorten($url)
    {

    }

    /**
     * {@inheritdoc}
     */
    public function expand($url)
    {

    }
}


text:
import calendar
import logging
import traceback
from datetime import datetime, timedelta

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import translation

from membership.models import BillingCycle, Bill, Payment, Membership

logger = logging.getLogger("membership.makebills")

class MembershipNotApproved(Exception):
    pass

def create_billingcycle(membership):
    """
    Creates a new billing cycle for a membership.

    If a previous billing cycle exists, the end date is used as the start
    date for the new one.  If a previous one doesn't exist, e.g. it is a new
    user, we use the time when they were approved.
    """
    try:
        if membership.status != 'A':
            logger.critical("%s not Approved. Cannot send bill" % repr(membership))
            raise MembershipNotApproved("%s not Approved. Cannot send bill" % repr(membership))
        try:
            newest_existing_billing_cycle = membership.billingcycle_set.latest('end')
        except ObjectDoesNotExist:
            newest_existing_billing_cycle = None

        if newest_existing_billing_cycle is not None:
            cycle_start = newest_existing_billing_cycle.end
        elif membership.approved is not None:
            cycle_start = membership.approved
        else:
            logger.critical("%s is missing the approved timestamp. Cannot send bill" % repr(membership))
            raise MembershipNotApproved("%s is missing the approved timestamp. Cannot send bill" % repr(membership))

        with transaction.atomic():
            billing_cycle = BillingCycle(membership=membership, start=cycle_start)
            billing_cycle.save()
            bill = Bill(billingcycle=billing_cycle)
            bill.save()
        bill.send_as_email()
        return billing_cycle
    except Exception as exc:
        logger.critical("%s" % traceback.format_exc())
        logger.critical("Transaction rolled back, billing cycle not created!")
        raise

def can_send_reminder(last_due_date, latest_recorded_payment):
    """
    Determine if we have recent payments so that we can be sure
    recent payments have been imported into the system.
    """
    if not settings.ENABLE_REMINDERS:
        return False
    can_send = True
    if not latest_recorded_payment:
        logger.critical("no payments in the database.")
        can_send = False
    else:
        if latest_recorded_payment > datetime.now():
            latest_recorded_payment = datetime.now()
        due_plus_margin = last_due_date + timedelta(days=settings.REMINDER_GRACE_DAYS)
        if latest_recorded_payment < due_plus_margin:
            can_send = False

    return can_send

def send_reminder(membership):
    billing_cycle = membership.billingcycle_set.latest('end')
    bill = Bill(billingcycle=billing_cycle)
    bill.reminder_count = billing_cycle.bill_set.count()
    bill.save()
    bill.send_as_email()
    return bill

def makebills():
    logger.info("Running makebills...")
    latest_recorded_payment = Payment.latest_payment_date()

    dt = datetime.now()
    last_of_month = datetime(dt.year, dt.month, calendar.monthrange(dt.year, dt.month)[1], 23, 59, 59)
    for member in Membership.objects.filter(status='A').filter(id__gt=0):
        # Billing cycles and bills
        cycles = member.billingcycle_set
        if cycles.count() == 0:
            cycle = create_billingcycle(member)
            logger.info("Created billing cycle %s for %s" % (repr(cycle), repr(member)))
        else:
            latest_cycle = cycles.latest("end")
            if latest_cycle.end <= last_of_month:
                cycle = create_billingcycle(member)
                logger.info("Created billing cycle %s for %s" %
                            (repr(cycle), repr(member)))

        # Reminders
        latest_cycle = member.billingcycle_set.latest('end')
        if not latest_cycle.is_paid:
            if latest_cycle.is_last_bill_late():
                last_due_date = latest_cycle.last_bill().due_date
                if can_send_reminder(last_due_date, latest_recorded_payment):
                    reminder = send_reminder(member)
                    logger.info("Sent reminder %s to %s." % (repr(reminder), repr(member)))
    logger.info("Done running makebills.")

class Command(BaseCommand):
    help = 'Find expiring billing cycles, send bills, send reminders'

    def handle(self, *args, **options):
        translation.activate(settings.LANGUAGE_CODE)
        makebills()


text:
using System;

namespace Renci.SshNet.Abstractions
{
    internal static class ThreadAbstraction
    {
        /// <summary>
        /// Suspends the current thread for the specified number of milliseconds.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended.</param>
        public static void Sleep(int millisecondsTimeout)
        {
#if FEATURE_THREAD_SLEEP
            System.Threading.Thread.Sleep(millisecondsTimeout);
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Delay(millisecondsTimeout).GetAwaiter().GetResult();
#else
            #error Suspend of the current thread is not implemented.
#endif
        }

        public static void ExecuteThreadLongRunning(Action action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

#if FEATURE_THREAD_TAP
            var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
            System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
#else
            new System.Threading.Thread(() => action())
            {
                IsBackground = true
            }.Start();
#endif
        }

        /// <summary>
        /// Executes the specified action in a separate thread.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public static void ExecuteThread(Action action)
        {
#if FEATURE_THREAD_THREADPOOL
            if (action == null)
                throw new ArgumentNullException("action");

            System.Threading.ThreadPool.QueueUserWorkItem(o => action());
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Run(action);
#else
            #error Execution of action in a separate thread is not implemented.
#endif
        }
    }
}


text:
#include "qandroidplatformtheme.h"
#include "qandroidplatformmenubar.h"
#include "qandroidplatformmenu.h"
#include "qandroidplatformmenuitem.h"
#include "qandroidplatformdialoghelpers.h"
#include <QVariant>
#include <QFileInfo>
#include <qandroidplatformintegration.h>

QAndroidPlatformTheme::QAndroidPlatformTheme(QAndroidPlatformNativeInterface *androidPlatformNativeInterface)
{
    m_androidPlatformNativeInterface = androidPlatformNativeInterface;
}

QPlatformMenuBar *QAndroidPlatformTheme::createPlatformMenuBar() const
{
    return new QAndroidPlatformMenuBar;
}

QPlatformMenu *QAndroidPlatformTheme::createPlatformMenu() const
{
    return new QAndroidPlatformMenu;
}

QPlatformMenuItem *QAndroidPlatformTheme::createPlatformMenuItem() const
{
    return new QAndroidPlatformMenuItem;
}

static inline int paletteType(QPlatformTheme::Palette type)
{
    switch (type) {
    case QPlatformTheme::ToolButtonPalette:
    case QPlatformTheme::ButtonPalette:
        return QPlatformTheme::ButtonPalette;

    case QPlatformTheme::CheckBoxPalette:
        return QPlatformTheme::CheckBoxPalette;

    case QPlatformTheme::RadioButtonPalette:
        return QPlatformTheme::RadioButtonPalette;

    case QPlatformTheme::ComboBoxPalette:
        return QPlatformTheme::ComboBoxPalette;

    case QPlatformTheme::TextEditPalette:
    case QPlatformTheme::TextLineEditPalette:
        return QPlatformTheme::TextLineEditPalette;

    case QPlatformTheme::ItemViewPalette:
        return QPlatformTheme::ItemViewPalette;

    default:
        return QPlatformTheme::SystemPalette;
    }
}

const QPalette *QAndroidPlatformTheme::palette(Palette type) const
{
    QHash<int, QPalette>::const_iterator it = m_androidPlatformNativeInterface->m_palettes.find(paletteType(type));
    if (it != m_androidPlatformNativeInterface->m_palettes.end())
        return &(it.value());
    return 0;
}

static inline int fontType(QPlatformTheme::Font type)
{
    switch (type) {
    case QPlatformTheme::LabelFont:
        return QPlatformTheme::SystemFont;

    case QPlatformTheme::ToolButtonFont:
        return QPlatformTheme::PushButtonFont;

    default:
        return type;
    }
}

const QFont *QAndroidPlatformTheme::font(Font type) const
{
    QHash<int, QFont>::const_iterator it = m_androidPlatformNativeInterface->m_fonts.find(fontType(type));
    if (it != m_androidPlatformNativeInterface->m_fonts.end())
        return &(it.value());

    // default in case the style has not set a font
    static QFont systemFont("Roboto", 14.0 * 100 / 72); // keep default size the same after changing from 100 dpi to 72 dpi
    if (type == QPlatformTheme::SystemFont)
        return &systemFont;
    return 0;
}

static const QLatin1String STYLES_PATH("/data/data/org.kde.necessitas.ministro/files/dl/style/");
static const QLatin1String STYLE_FILE("/style.json");

QVariant QAndroidPlatformTheme::themeHint(ThemeHint hint) const
{
    switch (hint) {
    case StyleNames:
        if (qgetenv("QT_USE_ANDROID_NATIVE_STYLE").toInt()
                && (!qgetenv("MINISTRO_ANDROID_STYLE_PATH").isEmpty()
                    || QFileInfo(STYLES_PATH
                                 + QLatin1String(qgetenv("QT_ANDROID_THEME_DISPLAY_DPI"))
                                 + STYLE_FILE).exists())) {
            return QStringList("android");
        }
        return QStringList("fusion");
        break;
    default:
        return QPlatformTheme::themeHint(hint);
    }
}

bool QAndroidPlatformTheme::usePlatformNativeDialog(QPlatformTheme::DialogType type) const
{
    if (type == MessageDialog)
        return qgetenv("QT_USE_ANDROID_NATIVE_DIALOGS").toInt() == 1;
    return false;
}

QPlatformDialogHelper *QAndroidPlatformTheme::createPlatformDialogHelper(QPlatformTheme::DialogType type) const
{
    switch (type) {
    case MessageDialog:
        return new QtAndroidDialogHelpers::QAndroidPlatformMessageDialogHelper;
    default:
        return 0;
    }
}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum EntityImportType {
  createEntityWithNewIdentifier ("createEntityWithNewIdentifier"),
  createEntityWithOriginalIdentifier ("createEntityWithOriginalIdentifier"),
  applyToEntitySpecified ("applyToEntitySpecified");

  @SuppressWarnings("unused")
  private final String val;
  private EntityImportType(String val)
  {
    this.val = val;
  }
}


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "gstdeinterlacemethod.h"
#include <string.h>

#define GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB	(gst_deinterlace_method_scaler_bob_get_type ())
#define GST_IS_DEINTERLACE_METHOD_SCALER_BOB(obj)		(G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB))
#define GST_IS_DEINTERLACE_METHOD_SCALER_BOB_CLASS(klass)	(G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB))
#define GST_DEINTERLACE_METHOD_SCALER_BOB_GET_CLASS(obj)	(G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB, GstDeinterlaceMethodScalerBobClass))
#define GST_DEINTERLACE_METHOD_SCALER_BOB(obj)		(G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB, GstDeinterlaceMethodScalerBob))
#define GST_DEINTERLACE_METHOD_SCALER_BOB_CLASS(klass)	(G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_DEINTERLACE_METHOD_SCALER_BOB, GstDeinterlaceMethodScalerBobClass))
#define GST_DEINTERLACE_METHOD_SCALER_BOB_CAST(obj)	((GstDeinterlaceMethodScalerBob*)(obj))

GType gst_deinterlace_method_scaler_bob_get_type (void);

typedef GstDeinterlaceSimpleMethod GstDeinterlaceMethodScalerBob;
typedef GstDeinterlaceSimpleMethodClass GstDeinterlaceMethodScalerBobClass;

static void
deinterlace_scanline_scaler_bob_packed (GstDeinterlaceSimpleMethod * self,
    guint8 * out, const GstDeinterlaceScanlineData * scanlines, guint size)
{
  memcpy (out, scanlines->t0, size);
}

static void
deinterlace_scanline_scaler_bob_planar_y (GstDeinterlaceSimpleMethod * self,
    guint8 * out, const GstDeinterlaceScanlineData * scanlines, guint size)
{
  memcpy (out, scanlines->t0, size);
}

static void
deinterlace_scanline_scaler_bob_planar_u (GstDeinterlaceSimpleMethod * self,
    guint8 * out, const GstDeinterlaceScanlineData * scanlines, guint size)
{
  memcpy (out, scanlines->t0, size);
}

static void
deinterlace_scanline_scaler_bob_planar_v (GstDeinterlaceSimpleMethod * self,
    guint8 * out, const GstDeinterlaceScanlineData * scanlines, guint size)
{
  memcpy (out, scanlines->t0, size);
}

G_DEFINE_TYPE (GstDeinterlaceMethodScalerBob, gst_deinterlace_method_scaler_bob,
    GST_TYPE_DEINTERLACE_SIMPLE_METHOD);

static void
gst_deinterlace_method_scaler_bob_class_init (GstDeinterlaceMethodScalerBobClass
    * klass)
{
  GstDeinterlaceMethodClass *dim_class = (GstDeinterlaceMethodClass *) klass;
  GstDeinterlaceSimpleMethodClass *dism_class =
      (GstDeinterlaceSimpleMethodClass *) klass;

  dim_class->fields_required = 2;
  dim_class->name = "Double lines";
  dim_class->nick = "scalerbob";
  dim_class->latency = 1;

  dism_class->interpolate_scanline_ayuv =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_yuy2 =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_yvyu =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_uyvy =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_nv12 =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_nv21 =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_argb =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_abgr =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_rgba =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_bgra =
      deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_rgb = deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_bgr = deinterlace_scanline_scaler_bob_packed;
  dism_class->interpolate_scanline_planar_y =
      deinterlace_scanline_scaler_bob_planar_y;
  dism_class->interpolate_scanline_planar_u =
      deinterlace_scanline_scaler_bob_planar_u;
  dism_class->interpolate_scanline_planar_v =
      deinterlace_scanline_scaler_bob_planar_v;
}

static void
gst_deinterlace_method_scaler_bob_init (GstDeinterlaceMethodScalerBob * self)
{
}


text:
#include "commonutil.h"

#if QT_VERSION >= 0x050500
bool g_messageVerbose = true;
#endif

// using stdc FILE* to write
bool writeStringToFile(const QString& str, const QString& fn)
{
    FILE* fp = fopen(fn.toUtf8().constData(), "w");
    if (fp == nullptr) {
        qDebug() << "cannot write file:" << fn;
        return false;
    }
    fprintf(fp, "%s", str.toUtf8().constData());
    fclose(fp);
    //qDebug() << "writeStringToFile(): write to" << fn;
    return true;
}

// using QFile to write
bool writeByteArrayToFile(const QByteArray& arr, const QString& fn)
{
    QFile outFile(fn);
    if (!outFile.open(QIODevice::WriteOnly)) {
        qWarning() << "fail to write file:" << fn;
        return false;
    }
    if ( outFile.write(arr) == -1 ) {
        return false;
    }
    return true;
}

bool readFileToByteArray(QByteArray& arr, const QString& fn)
{
    QFile inFile(fn);
    if (!inFile.open(QIODevice::ReadOnly)) {
        qWarning() << "fail to read file:" << fn;
        return false;
    }
    arr = inFile.readAll();
    return true;
}

void use_cout(const QString& msg)
{
    std::cout << msg.toUtf8().data() << std::endl;
}

#if QT_VERSION >= 0x050500/**
    \brief myMessageOutput() is customized message handler to redirect qDebug()
**/
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    Q_UNUSED(context);
    QString txt;
    QString prefix = QString("[%1][%2][%3] ")
                        .arg(QTime::currentTime().toString("HH:mm:ss.zzz"))
                        .arg(qApp->applicationName())
                        .arg(qApp->applicationPid());

    switch (type) {
        case QtDebugMsg:
            txt = prefix + QString("D: %1").arg(msg);
            if (g_messageVerbose)
                use_cout(txt);
            break;
        case QtWarningMsg:
            txt = prefix + QString("W: %1").arg(msg);
            use_cout(txt);
            break;
        case QtCriticalMsg:
            txt = prefix + QString("C: %1").arg(msg);
            use_cout(txt);
            break;
        case QtInfoMsg:
            txt = prefix + QString("I: %1").arg(msg);
            if (g_messageVerbose)
                use_cout(txt);
            break;
        case QtFatalMsg:
            txt = prefix + QString("F: %1").arg(msg);
            use_cout(txt);
            abort();
        default:
            break;
    }
}
#endif


text:
namespace BCompute
{
    public enum ParentalPair
    {
        DominantDominant,
        DominantHetero,
        DominantRecessive,
        HeteroHetero,
        HeteroRecessive,
        RecessiveRecessive
    }
}


text:
<?php

namespace TransilienService\TransilienControllerBundle\Renderers ;

class RendererStation extends RendererAbstract {

}


text:
import React from 'react';

import { Modal } from 'react-bootstrap';

import 'brace/mode/json';

import { IPipeline, IPipelineLock, IStage } from 'core/domain';
import { JsonUtils, noop } from 'core/utils';
import { IModalComponentProps, JsonEditor } from 'core/presentation';
import { PipelineJSONService } from '../../services/pipelineJSON.service';

export interface IEditPipelineJsonModalProps extends IModalComponentProps {
  pipeline: IPipeline;
  plan: IPipeline;
}

export interface IEditPipelineJsonModalState {
  errorMessage?: string;
  pipelineJSON: string;
  pipelinePlanJSON?: string;
  locked: IPipelineLock;
  isStrategy: boolean;
  activeTab: mode;
}

type mode = 'pipeline' | 'renderedPipeline';

export class EditPipelineJsonModal extends React.Component<IEditPipelineJsonModalProps, IEditPipelineJsonModalState> {
  public static defaultProps: Partial<IEditPipelineJsonModalProps> = {
    closeModal: noop,
    dismissModal: noop,
  };

  constructor(props: IEditPipelineJsonModalProps) {
    super(props);

    const copy = PipelineJSONService.clone(props.pipeline);
    let copyPlan: IPipeline;
    if (props.plan) {
      copyPlan = PipelineJSONService.clone(props.plan);
    }

    this.state = {
      pipelineJSON: JsonUtils.makeSortedStringFromObject(copy),
      pipelinePlanJSON: copyPlan ? JsonUtils.makeSortedStringFromObject(copyPlan) : null,
      locked: copy.locked,
      isStrategy: copy.strategy || false,
      activeTab: 'pipeline',
    };
  }

  private removeImmutableFields(pipeline: IPipeline): void {
    // no index signature on pipeline
    PipelineJSONService.immutableFields.forEach((k) => delete (pipeline as any)[k]);
  }

  private validatePipeline(pipeline: IPipeline): void {
    const refIds = new Set<string | number>();
    const badIds = new Set<string | number>();
    if (pipeline.stages) {
      pipeline.stages.forEach((stage: IStage) => {
        if (refIds.has(stage.refId)) {
          badIds.add(stage.refId);
        }
        refIds.add(stage.refId);
      });

      if (badIds.size) {
        throw new Error(
          `The refId property must be unique across stages.  Duplicate id(s): ${Array.from(badIds).toString()}`,
        );
      }
    }
  }

  private updatePipeline = (): void => {
    const { pipelineJSON } = this.state;
    const { pipeline } = this.props;

    try {
      const parsed = JSON.parse(pipelineJSON);
      parsed.appConfig = parsed.appConfig || {};

      this.validatePipeline(parsed);

      Object.keys(pipeline)
        .filter((k) => !PipelineJSONService.immutableFields.has(k) && !parsed.hasOwnProperty(k))
        .forEach((k) => delete (pipeline as any)[k]);
      this.removeImmutableFields(parsed);
      Object.assign(pipeline, parsed);

      this.props.closeModal();
    } catch (e) {
      this.setState({ errorMessage: e.message });
    }
  };

  private setActiveTab(activeTab: mode) {
    this.setState({ activeTab });
  }

  private updateJson = (pipelineJSON: string) => {
    this.setState({ pipelineJSON });
  };

  private onValidate = (errorMessage: string) => {
    this.setState({ errorMessage });
  };

  public render() {
    const { pipelineJSON, pipelinePlanJSON, locked, isStrategy, activeTab, errorMessage } = this.state;
    const invalid = !!errorMessage;
    const { dismissModal } = this.props;

    return (
      <>
        <Modal.Header>
          <Modal.Title>
            {!locked && Edit }
            {isStrategy ? 'Strategy' : 'Pipeline'} JSON
          </Modal.Title>
        </Modal.Header>
        <Modal.Body className="flex-fill">
          {!!pipelinePlanJSON && (

                 this.setActiveTab('pipeline')}>Configuration

                 this.setActiveTab('renderedPipeline')}>Rendered pipeline

          )}
          {activeTab === 'pipeline' && (
            <>

                The JSON below represents the {isStrategy ? 'strategy' : 'pipeline'} configuration in its persisted
                state.

              {!locked && (

                  Note: Clicking "Update {isStrategy ? 'Strategy' : 'Pipeline'}" below will not save
                  your changes to the server - it only updates the configuration within the browser, so you'll want to
                  verify your changes and click "Save Changes" when you're ready.

              )}
              <JsonEditor value={pipelineJSON} onChange={this.updateJson} onValidation={this.onValidate} />
            </>
          )}
          {activeTab === 'renderedPipeline' && (
            <>

This pipeline is based on a template. The JSON below represents the rendered pipeline.

              <form role="form" name="form" className="form-horizontal flex-fill">

                  <JsonEditor value={pipelinePlanJSON} readOnly={true} />

              </form>
            </>
          )}
        </Modal.Body>
        <Modal.Footer>
          {invalid && (

Error: {errorMessage}

          )}
          <button className="btn btn-default" onClick={() => dismissModal()}>
            Cancel
          </button>
          {!locked && (
            <button disabled={invalid} className="btn btn-primary" onClick={this.updatePipeline}>
               Update {isStrategy ? 'Strategy' : 'Pipeline'}
            </button>
          )}
        </Modal.Footer>
      </>
    );
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `src/event/mod.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>mod.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

1
2
3

pub use self::event_loop::{EventLoop, EventReceiver};

mod event_loop;

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
var baseURL;

function buscarTipoManoObra() {

	$("#frmBusquedaTipoManoObra").validate({

		rules : {
			descripcionTipoManoObra:"required"
		},

		messages : {
			descripcionTipoManoObra:"Este campo es requerido"
		},

		submitHandler : function(form) {

			$.ajax(form.action, {
				async : false,
				type : "POST",
				data : $(form).serialize(),
				success : function(contenido) {

					$("#listaTipoManoObra").html(contenido);
				}
			});
		}
	});
};

function eliminarTipoManoObra(idTipoManoObra) {

	var confirmacion = confirm("Desea eliminar permanentemente este PROCESO DE PRODUCCION?");

	if (confirmacion == true) {

		var baseURL, info;

		baseURL = $("#baseURL").val();

		$("#contenidoPrincipal").html("Cargando . . .");
		$.get(baseURL + "mantenimientoInterno/eliminarTipoManoObra?idTipoManoObra=" + idTipoManoObra, function(
				respuesta) {

			if (respuesta!=null && respuesta!=-1) {
				info = "Eliminado Correctamente";
			}
			else if(respuesta==-1){
				info="No se puede eliminar porque se hace referencia desde otro mantenimiento";
			}
			else {
				info = "No fue eliminado";
			}

			$.get(baseURL + "mantenimientoInterno/listarTiposManosObras?info=" + info, function(
					respuesta) {
				$("#contenidoPrincipal").html(respuesta);
				$("#title-page").html("Mantenimiento Proceso de Produccion - Listado");
			});

		});

	}
}

function limpiarTipoManoObra() {
	$("#descripcionTipoManoObra").val("");
	$("#contenidoPrincipal").html("Cargando . . .");
	$.get(baseURL + "mantenimientoInterno/listarTiposManosObras", function(respuesta) {
		$("#contenidoPrincipal").html(respuesta);
		$("#title-page").html("Mantenimiento Proceso de Produccion - Listado");

	}).fail(function() {
		$("#contenidoPrincipal").html("No se ha podido visualizar esta pagina");
	});
}

function editarTipoManoObra(idTipoManoObra) {

	$("#contenidoPrincipal").html("Cargando . . .");
	$.get(baseURL + "mantenimientoInterno/editarTipoManoObra/"+idTipoManoObra, function(respuesta) {
		$("#contenidoPrincipal").html(respuesta);
		$("#title-page").html("Mantenimiento Proceso de Produccion - Edicion");

	});
};

function nuevoTipoManoObra() {
	var baseURL;
    var idTipoManoObra=-1;
	baseURL = $("#baseURL").val();

	$("#contenidoPrincipal").html("Cargando . . .");
	$.get(baseURL + "mantenimientoInterno/editarTipoManoObra/"+idTipoManoObra, function(respuesta) {
		$("#contenidoPrincipal").html(respuesta);
		$("#title-page").html("Mantenimiento Proceso de Produccion - Nuevo");

	});

};


text:
#pragma once

#include "fboss/agent/platforms/wedge/WedgeProductInfo.h"
#include "fboss/agent/platforms/wedge/WedgePlatform.h"

#include <folly/Range.h>
#include <boost/container/flat_map.hpp>
#include <memory>
#include <unordered_map>

namespace facebook { namespace fboss {

class BcmSwitch;
class Wedge100Port;

class Wedge100Platform : public WedgePlatform {
 public:
  explicit Wedge100Platform(std::unique_ptr<WedgeProductInfo> productInfo);
  ~Wedge100Platform() override;

  InitPortMap initPorts() override;
  Wedge100Port* getPortFromFrontPanelNum(TransceiverID fpPort);
 private:
  Wedge100Platform(Wedge100Platform const &) = delete;
  Wedge100Platform& operator=(Wedge100Platform const &) = delete;

  typedef std::map<TransceiverID, PortID> FrontPanelMapping;

  std::map<std::string, std::string> loadConfig() override;
  std::unique_ptr<BaseWedgeI2CBus> getI2CBus() override;
  PortID fbossPortForQsfpChannel(int transceiver, int channel) override;
  FrontPanelMapping getFrontPanelMapping();
  folly::ByteRange defaultLedCode() override;

  FrontPanelMapping frontPanelMapping_;
};

}} // namespace facebook::fboss