text:
/*
 * ApplicationMasterProtocol.h
 *
 *  Created on: Jun 15, 2014
 *      Author: bwang
 */

#ifndef APPLICATIONMASTERPROTOCOL_H_
#define APPLICATIONMASTERPROTOCOL_H_

#include <iostream>
#include <list>

#include "rpc/RpcAuth.h"
#include "rpc/RpcConfig.h"
#include "rpc/RpcProtocolInfo.h"
#include "rpc/RpcServerInfo.h"
#include "rpc/RpcClient.h"

#include "common/SessionConfig.h"

#include "YARN_yarn_protos.pb.h"
#include "YARN_yarn_service_protos.pb.h"
#include "YARN_applicationmaster_protocol.pb.h"

#include "protocolrecords/RegisterApplicationMasterRequest.h"
#include "protocolrecords/RegisterApplicationMasterResponse.h"
#include "protocolrecords/AllocateRequest.h"
#include "protocolrecords/AllocateResponse.h"

#include "protocolrecords/FinishApplicationMasterRequest.h"
#include "protocolrecords/FinishApplicationMasterResponse.h"

#define APPLICATION_MASTER_VERSION 1
#define APPLICATION_MASTER_PROTOCOL "org.apache.hadoop.yarn.api.ApplicationMasterProtocolPB"
#define AMRM_TOKEN_KIND "YARN_AM_RM_TOKEN"

using namespace std;
using namespace google::protobuf;

using namespace hadoop::yarn;
using namespace Yarn::Internal;

namespace libyarn {

class ApplicationMasterProtocol {
public:
	ApplicationMasterProtocol(std::string & schedHost, std::string & schedPort,
			const std::string & tokenService, const SessionConfig & c,
			const RpcAuth & a);

	virtual ~ApplicationMasterProtocol();

	virtual RegisterApplicationMasterResponse registerApplicationMaster(
			RegisterApplicationMasterRequest &request);

	virtual AllocateResponse allocate(AllocateRequest &request);

	virtual FinishApplicationMasterResponse finishApplicationMaster(
			FinishApplicationMasterRequest &request);

private:
	void invoke(const RpcCall & call);

private:
    RpcAuth auth;
    RpcClient & client;
    RpcConfig conf;
    RpcProtocolInfo protocol;
    RpcServerInfo server;
    RpcChannel *channel;
};

}
#endif /* APPLICATIONMASTERPROTOCOL_H_ */


text:
package com.cuitrip.app.favorite;

import com.cuitrip.app.base.CtApiCallback;
import com.cuitrip.app.base.ListFetchCallback;

/**
 * Created by baziii on 15/8/10.
 */
public interface IFavoriteFetcher {
    void getFavoriteList(ListFetchCallback<FavoriteMode> itemListFetchCallback);
    void getFavoriteListWithMore(int pattern,ListFetchCallback<FavoriteMode> itemListFetchCallback);
    void deleteFavorite(FavoriteMode favoriteMode,CtApiCallback callback);
}

redpajama_set_name: RedPajamaGithub


text:
require 'rubygems'
require 'mysql'

# assumes the main DB has already been db:schema:load'd and db:seedy'd

MISSION_DBS = [{
    :mission => "Oklahoma 2011",
    :offset => 3200,
    :database => "cceom_cc_ok",
    :username => "cceom_cc_ok",
    :password => "02870107"
  },{
    :mission => "Liberia 2011",
    :offset => 27000,
    :database => "cceom_cc_lr",
    :username => "cceom_cc_lr",
    :password => "t1ckleME"
  },{
    :mission => "Liberia 2011 Runoff",
    :offset => 53000,
    :database => "cceom_cc_lr2",
    :username => "cceom_cc_lr2",
    :password => "t1ckleME"
  },{
    :mission => "Egypt 2012",
    :offset => 157000,
    :database => "cceom_elmo_eg",
    :username => "cceom_elmo_eg",
    :password => "t1ckleME"
  },{
    :mission => "Libya 2012",
    :offset => 17000,
    :database => "cceom_elmo_ly",
    :username => "cceom_elmo_ly",
    :password => "t1ckleME"
  }
]

MAIN_DB = { :database => "cceom_elmo_main", :username => "cceom_elmo_main", :password => "telefunkuku" }
TEMP_DB = { :database => "cceom_temp1", :username => "cceom_temp1", :password => "temp" }

TABLES_TO_COPY = %w(answers assignments broadcast_addressings broadcasts choices conditions form_types forms missions
 option_sets option_settings options questionings questions report_fields report_groupings report_reports responses settings translations users)

TABLES_TO_LOOKUP_IN_MAIN = {
  :question_types => ["questions.question_type_id", "report_fields.question_type_id"],
  :report_aggregations => ["report_reports.aggregation_id"],
  :report_response_attributes => ["report_fields.attrib_id"],
  :roles => ["assignments.role_id"]
}

dont_shift = TABLES_TO_LOOKUP_IN_MAIN.values.flatten.collect{|f| f.split(".").last}.uniq

def connect(params)
  Mysql.connect('localhost', params[:username], params[:password], params[:database])
end

def clear_tables(dbname, con)
  puts "Deleting from tables in #{dbname}"
  TABLES_TO_COPY.each do |t|
    #puts "Deleting from table #{dbname}.#{t}"
    con.query("DELETE FROM `#{t}`")
  end
end

def copy_tables(from_params, from_con, to_params, to_con)
  puts "Copying tables from #{from_params[:database]} to #{to_params[:database]}"

  # build & run cmd
  dump_cmd = "/usr/bin/mysqldump --skip-opt --no-create-info --extended-insert -u #{from_params[:username]} -p#{from_params[:password]} #{from_params[:database]} #{TABLES_TO_COPY.join(' ')}"
  load_cmd = "/usr/bin/mysql -u #{to_params[:username]} -p#{to_params[:password]} #{to_params[:database]}"
  %x[#{dump_cmd} > dump_tmp.sql]
  puts %x[#{dump_cmd} | #{load_cmd}]
end

# connect
temp_db = connect(TEMP_DB)
main_db = connect(MAIN_DB)

# delete all rows in appropriate tables from main db
clear_tables(MAIN_DB[:database], main_db)

max_ids_by_table = Hash[*TABLES_TO_COPY.collect{|t| [t, 0]}.flatten]

total_offset = 0

# for each db
MISSION_DBS.each_with_index do |mission_db_params, mission_db_idx|

  mission_db = connect(mission_db_params)

  # delete all rows in appropriate tables from temp db
  clear_tables(TEMP_DB[:database], temp_db)

  # copy everything from old mission db to the temp db
  copy_tables(mission_db_params, mission_db, TEMP_DB, temp_db)

  # rename the default mission to the correct name
  m_name = mission_db_params[:mission]
  m_compact_name = m_name.gsub(" ", "").downcase
  temp_db.query("UPDATE missions SET name = '#{m_name}', compact_name = '#{m_compact_name}'")

  # first we offset everything in all tables
  # for each table
  puts "Shifting id's"
  TABLES_TO_COPY.each do |t|

    # add offset to all ID's
    #puts "Shifting all #{t} ids by #{total_offset}"
    temp_db.query("UPDATE #{t} SET id = id + #{total_offset} + 1000000")
    temp_db.query("UPDATE #{t} SET id = id - 1000000")

    # update the offset
    #r = temp_db.query("SELECT MAX(id) FROM #{t}")
    #max_ids_by_table[t] = r.fetch_row[0].to_i
    #puts "Updated offset to #{max_ids_by_table[t]}"

    # for each col ending in _id, add offset
    res = temp_db.query("SHOW COLUMNS FROM #{t} WHERE Field LIKE '%_id'")
    while row = res.fetch_hash
      col = row['Field']

      # don't shift certain columns
      next if dont_shift.include?(col)

      #puts "Shifting all #{t}.#{col}'s by #{total_offset}"
      temp_db.query("UPDATE #{t} SET #{col} = #{col} + #{total_offset} + 1000000")
      temp_db.query("UPDATE #{t} SET #{col} = #{col} - 1000000")
    end

  end

  # then we go through the TABLES_TO_LOOKUP_IN_MAIN and lookup their values and build translatioin keys by name
  # for each table in TABLES_TO_LOOKUP_IN_MAIN
  TABLES_TO_LOOKUP_IN_MAIN.each_pair do |t, fks|
    name_to_id_hash = {}

    # lookup value in new table and store
    res = main_db.query("SELECT id, name FROM #{t}")
    while row = res.fetch_hash do
      name_to_id_hash[row['name']] = row['id']
    end
    puts "Built lookup hash #{name_to_id_hash.inspect}"

    # for each foreign key col
    fks.each do |fk|
      fk_table, fk_field = fk.split(".")
      # for each row in that col
      res = temp_db.query("SELECT id, #{fk_field} FROM #{fk_table}")
      while row = res.fetch_hash
        next if row[fk_field].nil?
        name = mission_db.query("SELECT name FROM #{t} WHERE #{t}.id = #{row[fk_field]}").fetch_row.first

        # hard-coded name substitutions
        name = "Coordinator" if name == "Program Staff" || name == "Admin"

        looked_up = name_to_id_hash[name]

        # update the value
        #puts "Updating #{fk} for row ##{row['id']} from #{row[fk_field]} (#{name}) to #{looked_up}"
        if looked_up.nil?
          puts "Couldn't find matching row when updating #{fk} for row ##{row['id']} from #{row[fk_field]} (#{name})"
        else
          temp_db.query("UPDATE #{fk_table} SET #{fk_field} = '#{looked_up}' WHERE id = '#{row['id']}'")
        end
      end
    end
  end

  # fix duplicate user logins
  # for each user in temp table
  res1 = temp_db.query("SELECT id, login FROM users")
  while new_user_row = res1.fetch_hash do

    # get its ID and login
    new_id, login = new_user_row['id'], new_user_row['login']

    # if there is an existing user in the main table with the same login name, get its ID
    res2 = main_db.query("SELECT id FROM users WHERE login = '#{login}'")
    if old_user_row = res2.fetch_hash
      old_id = old_user_row['id']

      # delete the row in the main table (so we replace with the newer one)
      puts "Deleting duplicate user #{login} from main db"
      main_db.query("DELETE FROM users WHERE id = '#{old_id}'")

      # update all responses, assignments, and broadcast addressings in the main db with a matching user_id to the newer ID
      %w(responses assignments broadcast_addressings).each do |ut|
        puts "Updating referring #{ut}'s in main db from #{old_id} to #{new_id}"
        main_db.query("UPDATE #{ut} SET user_id = '#{new_id}' WHERE user_id = '#{old_id}'")
      end
    end
  end

  # copy all rows in appropriate tables to the main table -- everything should match by now
  copy_tables(TEMP_DB, temp_db, MAIN_DB, main_db)

  total_offset += mission_db_params[:offset]
end

# update auto increment counters in all appropriate tables to appropriate values
puts "Updating auto incs to #{total_offset}"
TABLES_TO_COPY.each do |t|
  main_db.query("ALTER TABLE #{t} AUTO_INCREMENT = #{total_offset}")
end


text:
namespace RegexBot;

/// <summary>
/// Represents an error occurring when a module attempts to create a new guild state object
/// (that is, read or refresh its configuration).
/// </summary>
public class ModuleLoadException : Exception {
    /// <summary>
    /// Initializes this exception class with the specified error message.
    /// </summary>
    public ModuleLoadException(string message) : base(message) { }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SortedTableModel</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.gui

Class SortedTableModel

java.lang.Object

javax.swing.table.AbstractTableModel

weka.gui.SortedTableModel

All Implemented Interfaces:

java.io.Serializable, java.util.EventListener, javax.swing.event.TableModelListener, javax.swing.table.TableModel

Direct Known Subclasses:

ArffSortedTableModel

public class SortedTableModel
extends javax.swing.table.AbstractTableModel
implements javax.swing.event.TableModelListener

Represents a TableModel with sorting functionality.

Version:

$Revision: 10216 $

Author:

FracPete (fracpete at waikato dot ac dot nz)

See Also:

Serialized Form

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
SortedTableModel.SortContainer

Helper class for sorting the columns.

Constructor Summary

Constructors

Constructor and Description

SortedTableModel()

initializes with no model

SortedTableModel(javax.swing.table.TableModel model)

initializes with the given model

Method Summary

Methods

Modifier and Type
Method and Description

void
addMouseListenerToHeader(javax.swing.JTable table)

Adds a mouselistener to the header: left-click on the header sorts in
 ascending manner, using shift-left-click in descending manner.

int
getActualRow(int visibleRow)

Returns the actual underlying row the given visible one represents.

java.lang.Class<?>
getColumnClass(int columnIndex)

Returns the most specific superclass for all the cell values in the column.

int
getColumnCount()

Returns the number of columns in the model

java.lang.String
getColumnName(int columnIndex)

Returns the name of the column at columnIndex

javax.swing.table.TableModel
getModel()

returns the current model, can be null

int
getRowCount()

Returns the number of rows in the model.

java.lang.Object
getValueAt(int rowIndex,
          int columnIndex)

Returns the value for the cell at columnIndex and rowIndex.

boolean
isCellEditable(int rowIndex,
              int columnIndex)

Returns true if the cell at rowIndex and columnIndex is editable.

boolean
isSorted()

returns whether the table was sorted

void
setModel(javax.swing.table.TableModel value)

sets the model to use

void
setValueAt(java.lang.Object aValue,
          int rowIndex,
          int columnIndex)

Sets the value in the cell at columnIndex and rowIndex to aValue.

void
sort(int columnIndex)

sorts the table over the given column (ascending)

void
sort(int columnIndex,
    boolean ascending)

sorts the table over the given column, either ascending or descending

void
tableChanged(javax.swing.event.TableModelEvent e)

This fine grain notification tells listeners the exact range of cells,
 rows, or columns that changed.

Methods inherited from class javax.swing.table.AbstractTableModel

addTableModelListener, findColumn, fireTableCellUpdated, fireTableChanged, fireTableDataChanged, fireTableRowsDeleted, fireTableRowsInserted, fireTableRowsUpdated, fireTableStructureChanged, getListeners, getTableModelListeners, removeTableModelListener

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SortedTableModel

public SortedTableModel()

initializes with no model

SortedTableModel

public SortedTableModel(javax.swing.table.TableModel model)

initializes with the given model

Parameters:

model - the model to initialize the sorted model with

Method Detail

setModel

public void setModel(javax.swing.table.TableModel value)

sets the model to use

Parameters:

value - the model to use

getModel

public javax.swing.table.TableModel getModel()

returns the current model, can be null

Returns:

the current model

isSorted

public boolean isSorted()

returns whether the table was sorted

Returns:

true if the table was sorted

getActualRow

public int getActualRow(int visibleRow)

Returns the actual underlying row the given visible one represents. Useful
 for retrieving "non-visual" data that is also stored in a TableModel.

Parameters:

visibleRow - the displayed row to retrieve the original row for

Returns:

the original row

getColumnClass

public java.lang.Class<?> getColumnClass(int columnIndex)

Returns the most specific superclass for all the cell values in the column.

Specified by:

getColumnClass in interface javax.swing.table.TableModel

Overrides:

getColumnClass in class javax.swing.table.AbstractTableModel

Parameters:

columnIndex - the index of the column

Returns:

the class of the specified column

getColumnCount

public int getColumnCount()

Returns the number of columns in the model

Specified by:

getColumnCount in interface javax.swing.table.TableModel

Returns:

the number of columns in the model

getColumnName

public java.lang.String getColumnName(int columnIndex)

Returns the name of the column at columnIndex

Specified by:

getColumnName in interface javax.swing.table.TableModel

Overrides:

getColumnName in class javax.swing.table.AbstractTableModel

Parameters:

columnIndex - the column to retrieve the name for

Returns:

the name of the specified column

getRowCount

public int getRowCount()

Returns the number of rows in the model.

Specified by:

getRowCount in interface javax.swing.table.TableModel

Returns:

the number of rows in the model

getValueAt

public java.lang.Object getValueAt(int rowIndex,
                          int columnIndex)

Returns the value for the cell at columnIndex and rowIndex.

Specified by:

getValueAt in interface javax.swing.table.TableModel

Parameters:

rowIndex - the row

columnIndex - the column

Returns:

the value of the sepcified cell

isCellEditable

public boolean isCellEditable(int rowIndex,
                     int columnIndex)

Returns true if the cell at rowIndex and columnIndex is editable.

Specified by:

isCellEditable in interface javax.swing.table.TableModel

Overrides:

isCellEditable in class javax.swing.table.AbstractTableModel

Parameters:

rowIndex - the row

columnIndex - the column

Returns:

true if the cell is editable

setValueAt

public void setValueAt(java.lang.Object aValue,
              int rowIndex,
              int columnIndex)

Sets the value in the cell at columnIndex and rowIndex to aValue.

Specified by:

setValueAt in interface javax.swing.table.TableModel

Overrides:

setValueAt in class javax.swing.table.AbstractTableModel

Parameters:

aValue - the new value of the cell

rowIndex - the row

columnIndex - the column

sort

public void sort(int columnIndex)

sorts the table over the given column (ascending)

Parameters:

columnIndex - the column to sort over

sort

public void sort(int columnIndex,
        boolean ascending)

sorts the table over the given column, either ascending or descending

Parameters:

columnIndex - the column to sort over

ascending - ascending if true, otherwise descending

tableChanged

public void tableChanged(javax.swing.event.TableModelEvent e)

This fine grain notification tells listeners the exact range of cells,
 rows, or columns that changed.

Specified by:

tableChanged in interface javax.swing.event.TableModelListener

Parameters:

e - the event

addMouseListenerToHeader

public void addMouseListenerToHeader(javax.swing.JTable table)

Adds a mouselistener to the header: left-click on the header sorts in
 ascending manner, using shift-left-click in descending manner.

Parameters:

table - the table to add the listener to

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
var arDrone = require('ar-drone');
var client  = arDrone.createClient();
var http = require("http");
var stream  = require("dronestream");

var server = http.createServer(function(req, res) {
  require("fs").createReadStream(__dirname + "/index.html").pipe(res);
});

stream.listen(server);
server.listen(3000);

console.log("access! localhost:3000");
console.log("try! takeoff() land() stop() front(0.1) back(0.1) left(0.1) right(0.1) clockwise(0.3) counterClockwise(0.3) up(0.1) down(0.1) animate('flipRight', 10) ");

console.log("You have control. : drone> ");

client.createRepl();


text:
#ifndef NVIM_BRIDGE_DATA_HPP
#define NVIM_BRIDGE_DATA_HPP

#include <SFML/System/String.hpp>

#include <mutex>
#include <atomic>

/* BridgeData struct keeps data used both by the bindings
 * and by nvim::Neovim to support communication between
 * GUI and nvim.
 */

namespace nvim
{
    class Neovim;
    class DataHolder;

    //Contains stuff somehow useful for managing
    //data flows between the Python side and the
    //C++ side.
    struct BridgeData
    {
        BridgeData()
        {
            newDimensionsRows = -1;
            newDimensionsCols = -1;
            quitFlag = false;
        }

        nvim::Neovim
            *neovim = nullptr;
        nvim::DataHolder
            *dataHolder = nullptr;

        std::mutex updateMutex,
             resizeMutex,
             nvimInputMutex; //UI -> Nvim input

        std::atomic<int32_t>
             newDimensionsRows,
             newDimensionsCols;

        std::atomic<bool>
             quitFlag;

        sf::String
             userInput;

        std::string
             commandLineArgument;
    };
}

#endif


text:
"""
=============================
Template for query strategies
=============================

The first two arguments of a query strategy function is always the estimator and the pool
of instances to be queried from. Additional arguments are accepted as keyword arguments.
A valid query strategy function always returns indices of the queried
instances.

def custom_query_strategy(classifier, X, a_keyword_argument=42):
    # measure the utility of each instance in the pool
    utility = utility_measure(classifier, X)

    # select and return the indices of the instances to be queried
    return select_instances(utility)

This function can be used in the active learning workflow.

learner = ActiveLearner(classifier, query_strategy=custom_query_strategy)
query_idx, query_instance = learner.query(X_pool, a_keyword_argument=42*42)

In this example, we will construct a custom query function by combining classifier uncertainty
and classifier margin.
"""

import numpy as np
import matplotlib.pyplot as plt

from modAL.utils.combination import make_linear_combination, make_product
from modAL.utils.selection import multi_argmax
from modAL.uncertainty import classifier_uncertainty, classifier_margin
from modAL.models import ActiveLearner
from sklearn.datasets import make_blobs
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF

# generating the data
centers = np.asarray([[-2, 3], [0.5, 5], [1, 1.5]])
X, y = make_blobs(
    n_features=2, n_samples=1000, random_state=0, cluster_std=0.7,
    centers=centers
)
# visualizing the dataset
with plt.style.context('seaborn-white'):
    plt.figure(figsize=(7, 7))
    plt.scatter(x=X[:, 0], y=X[:, 1], c=y, cmap='viridis', s=50)
    plt.title('The dataset')
    plt.show()

# initial training data
initial_idx = np.random.choice(range(len(X)), size=20)
X_training, y_training = X[initial_idx], y[initial_idx]

# initializing the learner
learner = ActiveLearner(
    estimator=GaussianProcessClassifier(1.0 * RBF(1.0)),
    X_training=X_training, y_training=y_training
)

# creating new utility measures by linear combination and product
# linear_combination will return 1.0*classifier_uncertainty + 1.0*classifier_margin
linear_combination = make_linear_combination(
    classifier_uncertainty, classifier_margin,
    weights=[1.0, 1.0]
)
# product will return (classifier_uncertainty**0.5)*(classifier_margin**0.1)
product = make_product(
    classifier_uncertainty, classifier_margin,
    exponents=[0.5, 0.1]
)

# visualizing the different utility metrics
with plt.style.context('seaborn-white'):
    utilities = [
        (1, classifier_uncertainty(learner, X), 'Classifier uncertainty'),
        (2, classifier_margin(learner, X), 'Classifier margin'),
        (3, linear_combination(learner, X), '1.0*uncertainty + 1.0*margin'),
        (4, product(learner, X), '(uncertainty**0.5)*(margin**0.5)')
    ]

    plt.figure(figsize=(18, 14))
    for idx, utility, title in utilities:
        plt.subplot(2, 2, idx)
        plt.scatter(x=X[:, 0], y=X[:, 1], c=utility, cmap='viridis', s=50)
        plt.title(title)
        plt.colorbar()

    plt.show()

# defining the custom query strategy, which uses the linear combination of
# classifier uncertainty and classifier margin
def custom_query_strategy(classifier, X, n_instances=1):
    utility = linear_combination(classifier, X)
    return multi_argmax(utility, n_instances=n_instances)

custom_query_learner = ActiveLearner(
    estimator=GaussianProcessClassifier(1.0 * RBF(1.0)),
    query_strategy=custom_query_strategy,
    X_training=X_training, y_training=y_training
)

# pool-based sampling
n_queries = 20
for idx in range(n_queries):
    query_idx, query_instance = custom_query_learner.query(X, n_instances=2)
    custom_query_learner.teach(
        X=X[query_idx].reshape(-1, 2),
        y=y[query_idx].reshape(-1, )
    )


text:
layout: examHandoutNoName
num: e02
ready: true
desc: "Midterm Handout"
exam_date: 2018-05-15 15:30:00.00
---

# Test cases for indexLargestEvenInt

`indexLargestEvenInt` should return the index
in the list of the largest even integer.   If there
are no even integers in the list, it should return
`None`.

{% highlight python linenos %}
list1 = [22,55,88,33,66]
list2 = [33,11,77]
list3 = [33,34,11,66,99]
list4 = [44,11,22]

def test_1():
    assert indexLargestEvenInt(list1)==2

def test_2():
    assert indexLargestEvenInt(list2)==None

def test_3():
    assert indexLargestEvenInt(list3)==3

def test_4():
    assert indexLargestEvenInt(list4)==0

{% endhighlight  %}

# Code for `indexLargestEvenInt_a`

{% highlight python linenos %}
def indexLargestEvenInt_a(ilist):
    "index of largest even integer; None if no even ints"
    if type(ilist)!=list:
        raise ValueError("not a list")
    answer=None
    for x in ilist:
      if x%2 == 0:
        if answer==None or x > answer:
          answer = x
    return answer
{% endhighlight %}

# Code for `indexLargestEvenInt_b`

{% highlight python linenos %}
def indexLargestEvenInt_b(ilist):
    if type(ilist)!=list:
        raise ValueError("not a list")
    answer=None
    for i in range(len(ilist)):
      if ilist[i]%2 == 0:
        if answer==None or ilist[i] > ilist[answer]:
          answer = i
    return answer

{% endhighlight %}

Handout for {{site.course}}, Final Exam, {{site.qtr}}, Page 2

# Code for `indexLargestEvenInt_c`

{% highlight python linenos %}
def indexLargestEvenInt_c(ilist):

    if type(ilist)!=list:
        raise ValueError("not a list")
    answer=None
    for i in range(len(ilist)):
      if ilist[i]%2 == 0:
        if answer==None or ilist[i] > ilist[answer]:
          answer = i
      return answer

{% endhighlight %}

# Code for `indexLargestEvenInt_d`

{% highlight python linenos %}
def indexLargestEvenInt_d(ilist):

    if type(ilist)!=list:
        raise ValueError("not a list")
    answer=None
    for x in ilist:
      if (x%2 == 0) and x > answer:
        answer = x
    return answer

{% endhighlight %}


text:
using System.ComponentModel.Composition;
using DevExpress.CodeRush.Common;

namespace CR_QuickPair
{
  [Export(typeof(IVsixPluginExtension))]
  public class CR_QuickPairExtension : IVsixPluginExtension { }
}


text:
@interface FakeMPAdServerCommunicator : MPAdServerCommunicator

@property (nonatomic, assign) BOOL loading;
@property (nonatomic, strong) NSURL *loadedURL;
@property (nonatomic, assign) BOOL cancelled;

- (void)receiveConfiguration:(MPAdConfiguration *)configuration;
- (void)failWithError:(NSError *)error;

- (void)resetLoadedURL;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Boilerplate.Models
{
    public class Foodstuff : BaseModel
    {
        public string Name { get; set; }

        public DateTime BestBeforeDate { get; set; }
    }
}


text:
module RailsAdmin
  class FormBuilder < ::ActionView::Helpers::FormBuilder
    include ::NestedForm::BuilderMixin

    def generate(options = {})
      without_field_error_proc_added_div do
        options.reverse_merge!({
          :action => @template.controller.params[:action],
          :model_config => @template.instance_variable_get(:@model_config),
          :nested_in => false
        })

        if options[:nested_in]
          action = :nested
        elsif @template.request.format == 'text/javascript'
          action = :modal
        else
          action = options[:action]
        end

        groups = options[:model_config].send(action).with(:form => self, :object => @object, :view => @template, :controller => @template.controller).visible_groups

        object_infos +
        groups.map do |fieldset|
          fieldset_for fieldset, options[:nested_in]
        end.join.html_safe +
        (options[:nested_in] ? '' : @template.render(:partial => 'rails_admin/main/submit_buttons'))
      end
    end

    def fieldset_for fieldset, nested_in
      if (fields = fieldset.with(:form => self, :object => @object, :view => @template, :controller => @template.controller).visible_fields).length > 0
        @template.content_tag :fieldset do
          contents = []
          contents << @template.content_tag(:legend, %{ #{fieldset.label}}.html_safe, :style => "#{fieldset.name == :default ? 'display:none' : ''}")
          contents << @template.content_tag(:p, fieldset.help) if fieldset.help.present?
          contents << fields.map{ |field| field_wrapper_for(field, nested_in) }.join
          contents.join.html_safe
        end
      end
    end

    def field_wrapper_for field, nested_in
      if field.label
        # do not show nested field if the target is the origin
        unless field.inverse_of.presence && field.inverse_of == nested_in &&
          @template.instance_variable_get(:@model_config).abstract_model == field.associated_model_config.abstract_model
          @template.content_tag(:div, :class => "control-group #{field.type_css_class} #{field.css_class} #{'error' if field.errors.present?}", :id => "#{dom_id(field)}_field") do
            label(field.method_name, field.label, :class => 'control-label') +
            (field.nested_form ? field_for(field) : input_for(field))
          end
        end
      else
        (field.nested_form ? field_for(field) : input_for(field))
      end
    end

    def input_for field
      @template.content_tag(:div, :class => 'controls') do
        field_for(field) +
        errors_for(field) +
        help_for(field)
      end
    end

    def errors_for field
      field.errors.present? ? @template.content_tag(:span, "#{field.label} #{field.errors.to_sentence}", :class => 'help-inline') : ''.html_safe
    end

    def help_for field
      field.help.present? ? @template.content_tag(:p, field.help, :class => 'help-block') : ''.html_safe
    end

    def field_for field
      if field.read_only?
        field.pretty_value.to_s.html_safe
      else
        field.render
      end
    end

    def object_infos
      model_config = RailsAdmin.config(object)
      model_label = model_config.label
      object_label = (object.new_record? ? I18n.t('admin.form.new_model', :name => model_label) : object.send(model_config.object_label_method).presence || "#{model_config.label} ##{object.id}")
      %{}.html_safe
    end

    def jquery_namespace field
      %{#{(@template.controller.params[:modal] ? '#modal ' : '')}##{dom_id(field)}_field}
    end

    def dom_id field
      (@dom_id ||= {})[field.name] ||=
        [
          @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, ""),
          options[:index],
          field.method_name
        ].reject(&:blank?).join('_')
    end

    def dom_name field
      (@dom_name ||= {})[field.name] ||= %{#{@object_name}#{options[:index] && "[#{options[:index]}]"}[#{field.method_name}]#{field.is_a?(Config::Fields::Association) && field.multiple? ? '[]' : ''}}
    end

    protected
      def without_field_error_proc_added_div
        default_field_error_proc = ::ActionView::Base.field_error_proc
        begin
          ::ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| html_tag }
          yield
        ensure
          ::ActionView::Base.field_error_proc = default_field_error_proc
        end
      end
  end
end


text:
var common = {
  getFormJSON: function(ele) {
    if (ele.jquery === undefined)
      ele = $(ele);
    var arr = ele.serializeArray();
    var res = {};
    arr.forEach(function(t){
      res[t.name] = t.value;
    });
    return JSON.stringify(res);
  },
  postJSON: function(url, data, success, error) {

    if (typeof data === 'function') {
      error   = success;
      success = data;
      data    = '';
    }
    $.ajax({
      type: 'POST',
      contentType: "application/json",
      url: url,
      data: data,
      success: success,
      error: error
    });
  }

}


text:
function run {
   if (command -v $1 && ! pgrep $1); then
     $@&
   fi
}

## run (only once) processes which spawn with different name
if (command -v gnome-keyring-daemon && ! pgrep gnome-keyring-d); then
    gnome-keyring-daemon --daemonize --login &
fi
if (command -v start-pulseaudio-x11 && ! pgrep pulseaudio); then
    start-pulseaudio-x11 &
fi
if (command -v /usr/lib/mate-polkit/polkit-mate-authentication-agent-1 && ! pgrep polkit-mate-aut) ; then
    /usr/lib/mate-polkit/polkit-mate-authentication-agent-1 &
fi
if (command -v  xfce4-power-manager && ! pgrep xfce4-power-man) ; then
    xfce4-power-manager &
fi

run xfsettingsd
run nm-applet
run light-locker
run thunar --daemon
run pa-applet
run pamac-tray
run nitrogen --restore
run spotify
run keepassxc
run cadence --minimized
run mullvad-vpn
run syncthing-gtk

## The following are not included in minimal edition by default
## but autorun.sh will pick them up if you install them

if (command -v system-config-printer-applet && ! pgrep applet.py ); then
  system-config-printer-applet &
fi

run compton --shadow-exclude '!focused'
run blueman-applet
run msm_notifier


text:
/*
 * @author ztomchenco
 */

jaspersoft.components.AuthorityModel = (function (jQuery, _, Backbone, Engine) {

    return Backbone.Model.extend({

            defaults: {
                items: []
            },

            url: function(){
                return Engine.renderUrl(this.urlTemplate, this.context, true);
            },

            parse: function(responce) {
                return {items:(responce.role)? responce.role : responce.user };
            },

            defaultErrorHandler: function(model, xnr){
                var data;
                try{
                    data = jQuery.parseJSON(xnr.responseText);
                }catch (error){ // this is not JSON
                    data = null;
                }
                this.trigger("error:server",xnr.status, data, model);
            },

            setContext:  function(context){
                this.context = context;
                this.fetch({error:_.bind(this.defaultErrorHandler, this)});
            }

        }, {
            instance: function(urlTemplate, context){
                var inst = new this();
                inst.urlTemplate = urlTemplate;
                context && inst.setContext(context);
                return inst;
            }
        });
})(
    jQuery,
    _,
    Backbone,
    jaspersoft.components.templateEngine
);


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zxh.ssm.module.whole.mapper.PatientInformationMapper" >
  <resultMap id="BaseResultMap" type="com.zxh.ssm.module.whole.pojo.PatientInformation" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="year" property="year" jdbcType="INTEGER" />
    <id column="cardID" property="cardid" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="birthday" property="birthday" jdbcType="DATE" />
    <result column="age" property="age" jdbcType="VARCHAR" />
    <result column="workUnit" property="workunit" jdbcType="VARCHAR" />
    <result column="tel" property="tel" jdbcType="VARCHAR" />
    <result column="belongs" property="belongs" jdbcType="VARCHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
    <result column="career" property="career" jdbcType="VARCHAR" />
    <result column="addrNationID" property="addrnationid" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    year, cardID, name, sex, birthday, age, workUnit, tel, belongs, address, career,
    addrNationID
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformationExample" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from patient_information
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformationKey" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <include refid="Base_Column_List" />
    from patient_information
    where year = #{year,jdbcType=INTEGER}
      and cardID = #{cardid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformationKey" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from patient_information
    where year = #{year,jdbcType=INTEGER}
      and cardID = #{cardid,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformationExample" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from patient_information
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformation" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into patient_information (year, cardID, name,
      sex, birthday, age, workUnit,
      tel, belongs, address,
      career, addrNationID)
    values (#{year,jdbcType=INTEGER}, #{cardid,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
      #{sex,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{age,jdbcType=VARCHAR}, #{workunit,jdbcType=VARCHAR},
      #{tel,jdbcType=VARCHAR}, #{belongs,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR},
      #{career,jdbcType=VARCHAR}, #{addrnationid,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformation" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into patient_information
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="year != null" >
        year,
      </if>
      <if test="cardid != null" >
        cardID,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="birthday != null" >
        birthday,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="workunit != null" >
        workUnit,
      </if>
      <if test="tel != null" >
        tel,
      </if>
      <if test="belongs != null" >
        belongs,
      </if>
      <if test="address != null" >
        address,
      </if>
      <if test="career != null" >
        career,
      </if>
      <if test="addrnationid != null" >
        addrNationID,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="year != null" >
        #{year,jdbcType=INTEGER},
      </if>
      <if test="cardid != null" >
        #{cardid,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="birthday != null" >
        #{birthday,jdbcType=DATE},
      </if>
      <if test="age != null" >
        #{age,jdbcType=VARCHAR},
      </if>
      <if test="workunit != null" >
        #{workunit,jdbcType=VARCHAR},
      </if>
      <if test="tel != null" >
        #{tel,jdbcType=VARCHAR},
      </if>
      <if test="belongs != null" >
        #{belongs,jdbcType=VARCHAR},
      </if>
      <if test="address != null" >
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="career != null" >
        #{career,jdbcType=VARCHAR},
      </if>
      <if test="addrnationid != null" >
        #{addrnationid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformationExample" resultType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select count(*) from patient_information
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update patient_information
    <set >
      <if test="record.year != null" >
        year = #{record.year,jdbcType=INTEGER},
      </if>
      <if test="record.cardid != null" >
        cardID = #{record.cardid,jdbcType=INTEGER},
      </if>
      <if test="record.name != null" >
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.sex != null" >
        sex = #{record.sex,jdbcType=VARCHAR},
      </if>
      <if test="record.birthday != null" >
        birthday = #{record.birthday,jdbcType=DATE},
      </if>
      <if test="record.age != null" >
        age = #{record.age,jdbcType=VARCHAR},
      </if>
      <if test="record.workunit != null" >
        workUnit = #{record.workunit,jdbcType=VARCHAR},
      </if>
      <if test="record.tel != null" >
        tel = #{record.tel,jdbcType=VARCHAR},
      </if>
      <if test="record.belongs != null" >
        belongs = #{record.belongs,jdbcType=VARCHAR},
      </if>
      <if test="record.address != null" >
        address = #{record.address,jdbcType=VARCHAR},
      </if>
      <if test="record.career != null" >
        career = #{record.career,jdbcType=VARCHAR},
      </if>
      <if test="record.addrnationid != null" >
        addrNationID = #{record.addrnationid,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update patient_information
    set year = #{record.year,jdbcType=INTEGER},
      cardID = #{record.cardid,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      sex = #{record.sex,jdbcType=VARCHAR},
      birthday = #{record.birthday,jdbcType=DATE},
      age = #{record.age,jdbcType=VARCHAR},
      workUnit = #{record.workunit,jdbcType=VARCHAR},
      tel = #{record.tel,jdbcType=VARCHAR},
      belongs = #{record.belongs,jdbcType=VARCHAR},
      address = #{record.address,jdbcType=VARCHAR},
      career = #{record.career,jdbcType=VARCHAR},
      addrNationID = #{record.addrnationid,jdbcType=INTEGER}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformation" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update patient_information
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="birthday != null" >
        birthday = #{birthday,jdbcType=DATE},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=VARCHAR},
      </if>
      <if test="workunit != null" >
        workUnit = #{workunit,jdbcType=VARCHAR},
      </if>
      <if test="tel != null" >
        tel = #{tel,jdbcType=VARCHAR},
      </if>
      <if test="belongs != null" >
        belongs = #{belongs,jdbcType=VARCHAR},
      </if>
      <if test="address != null" >
        address = #{address,jdbcType=VARCHAR},
      </if>
      <if test="career != null" >
        career = #{career,jdbcType=VARCHAR},
      </if>
      <if test="addrnationid != null" >
        addrNationID = #{addrnationid,jdbcType=INTEGER},
      </if>
    </set>
    where year = #{year,jdbcType=INTEGER}
      and cardID = #{cardid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zxh.ssm.module.whole.pojo.PatientInformation" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update patient_information
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      birthday = #{birthday,jdbcType=DATE},
      age = #{age,jdbcType=VARCHAR},
      workUnit = #{workunit,jdbcType=VARCHAR},
      tel = #{tel,jdbcType=VARCHAR},
      belongs = #{belongs,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR},
      career = #{career,jdbcType=VARCHAR},
      addrNationID = #{addrnationid,jdbcType=INTEGER}
    where year = #{year,jdbcType=INTEGER}
      and cardID = #{cardid,jdbcType=INTEGER}
  </update>
</mapper>


text:
package de.mpg.mpdl.service.rest.fits;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.grizzly2.servlet.GrizzlyWebContainerFactory;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.spi.TestContainer;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;

import javax.ws.rs.ProcessingException;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;

/**
 * The class overrides TestContainerFactory with GrizzlyWebContainerFactory. The GrizzlyWebContainer fully
 * supports HttpServlet, that is needed to test @Context injection variables in tests
*
 * @author vmakarenko
 *
* */
public class MyTestContainerFactory implements TestContainerFactory {
    @Override
    public TestContainer create(final URI baseUri, DeploymentContext deploymentContext) throws IllegalArgumentException {
        return new TestContainer() {
            private HttpServer server;

            @Override
            public ClientConfig getClientConfig() {
                return null;
            }

            @Override
            public URI getBaseUri() {
                return baseUri;
            }

            @Override
            public void start() {
                try {
                    this.server = GrizzlyWebContainerFactory.create(
                            baseUri, Collections.singletonMap("jersey.config.server.provider.packages", "de.mpg.mpdl.service.rest.fits")
                    );
                } catch (ProcessingException e) {
                    throw new TestContainerException(e);
                } catch (IOException e) {
                    throw new TestContainerException(e);
                }
            }

            @Override
            public void stop() {
                this.server.stop();
            }
        };

    }

}


text:
package org.mojavemvc.tests;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;
import org.mojavemvc.util.RouteHelper;

/**
 * @author Luis Antunes
 */
public class TestRouteHelper {

    @Test
    public void getPathElements_NoController_NoAction_NoParamPath() {
        String[] expected = new String[]{""};
        String[] actual = RouteHelper.getPathElements("/");
        assertTrue(Arrays.equals(expected, actual));
    }

    @Test
    public void getPathElements_WithController_WithAction_WithParamPath() {
        String[] expected = new String[]{"cntrl","actn","clients",":id"};
        String[] actual = RouteHelper.getPathElements("/cntrl/actn/clients/:id");
        assertTrue(Arrays.equals(expected, actual));
    }

    @Test
    public void getPathElements_NoController_NoAction_WithParamPath() {
        String[] expected = new String[]{"clients",":id"};
        String[] actual = RouteHelper.getPathElements("/clients/:id");
        assertTrue(Arrays.equals(expected, actual));
    }

    @Test
    public void getPathElements_NoController_NoAction_WithParamPathWithRegex() {
        String[] expected = new String[]{"clients",":id<[0-9]+>"};
        String[] actual = RouteHelper.getPathElements("/clients/:id<[0-9]+>");
        assertTrue(Arrays.equals(expected, actual));
    }

    @Test
    public void escapeNonCustomRegex() {
        String path = "/cntrl/[](){}*^?$.\\/a+b/:id<[^/]+>/:name<[a-z]+>";
        String expected =
                "/cntrl/\\[\\]\\(\\)\\{\\}\\*\\^\\?\\$\\.\\\\/a\\+b/:id<[^/]+>/:name<[a-z]+>";
        String actual = RouteHelper.escapeNonCustomRegex(path);
        assertEquals(expected, actual);
    }
}


text:
<!DOCTYPE html>

        <title>Simple Map</title>
        <meta name="viewport" content="initial-scale=1.0">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">

        <link rel="stylesheet" href="css/normalize.css">

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

SnapPark

            Find a spot in a snap

              View Mode
            <select id="viewModeSelect">
                <option selected value="nearest">Only Show Nearest</option>
                <option value="all">Show All</option>
            </select>

                 Show Reserved Spaces

            <input type="checkbox" id="showReservedCheckBox" value="first_checkbox">

How do I use this App?

                Your current location is shown with an arrow in the middle of the map.  By default, the nearest available parking spots will be shown.

To get details about a spot, click the icon.

To reserve a spot, click it, select an amount of time you want it for and click "Reserve This Spot".

To recenter the map, click the map or drag the location arrow.

Change what is displayed by adjusting the controls in the upper right corner.


text:
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# Google Cloud Functions - Hello World sample

See:

* [Cloud Functions Hello World tutorial][tutorial]
* [Cloud Functions Hello World sample source code][code]

[tutorial]: https://cloud.google.com/functions/docs/quickstart
[code]: index.js

## Deploy and run the sample

See the [Cloud Functions Hello World tutorial][tutorial].

**Note:** in order for the tests to run properly, you'll have to deploy some of the sample functions:

```
gcloud functions deploy helloHttp --runtime [YOUR_RUNTIME] --trigger-http
gcloud functions deploy helloPubSub --trigger-topic $FUNCTIONS_TOPIC --runtime [YOUR_RUNTIME]
gcloud functions deploy helloGCS --runtime [YOUR_RUNTIME] --trigger-resource $FUNCTIONS_DELETABLE_BUCKET --trigger-event providers/cloud.storage/eventTypes/object.change
```

* Replace `[YOUR_RUNTIME]` with the name of the runtime you are using. For a
complete list, see the [gcloud reference](https://cloud.google.com/sdk/gcloud/reference/functions/deploy#--runtime).

## Run the tests

1. Read and follow the [prerequisites](../../../README.md#prerequisites).

1. Install dependencies:

        npm install

1. Set the following environment variables:

        export GCF_REGION=us-central1
        export FUNCTIONS_TOPIC=[YOUR_PUBSUB_TOPIC]
        export FUNCTIONS_DELETABLE_BUCKET=[YOUR_CLOUD_STORAGE_BUCKET]  # will be deleted by tests!

1. Run the tests:

        npm test


text:
/*!
 * \file src/runtime/contrib/arm_compute_lib/acl_allocator.cc
 * \brief ACL Allocator implementation that requests memory from TVM.
 */

#include "acl_allocator.h"

namespace tvm {
namespace runtime {
namespace contrib {

void* ACLAllocator::allocate(size_t size, size_t alignment) {
  ICHECK_GT(size, 0) << "Cannot allocate size less than or equal to zero";
  return this->device_api_->AllocWorkspace(this->device_, size, {});
}

void ACLAllocator::free(void* ptr) { this->device_api_->FreeWorkspace(this->device_, ptr); }

std::unique_ptr<arm_compute::IMemoryRegion> ACLAllocator::make_region(size_t size,
                                                                      size_t alignment) {
  return std::make_unique<ACLMemoryRegion>(size, alignment);
}

ACLMemoryRegion::ACLMemoryRegion(size_t size, size_t alignment)
    : IMemoryRegion(size), ptr_(nullptr) {
  if (size != 0) {
    this->ptr_ = this->device_api_->AllocDataSpace(this->device_, size, alignment, {});
  }
}

ACLMemoryRegion::ACLMemoryRegion(void* ptr, size_t size)
    : IMemoryRegion(size), ptr_(nullptr), is_subregion_(true) {
  if (size != 0) {
    this->ptr_ = ptr;
  }
}

ACLMemoryRegion::~ACLMemoryRegion() {
  if (this->ptr_ != nullptr && !is_subregion_) {
    this->device_api_->FreeDataSpace(this->device_, this->ptr_);
  }
}

std::unique_ptr<arm_compute::IMemoryRegion> ACLMemoryRegion::extract_subregion(size_t offset,
                                                                               size_t size) {
  if (this->ptr_ != nullptr && (offset < _size) && (_size - offset >= size)) {
    return std::make_unique<ACLMemoryRegion>(static_cast<uint8_t*>(this->ptr_) + offset, size);
  } else {
    return nullptr;
  }
}

}  // namespace contrib
}  // namespace runtime
}  // namespace tvm


text:
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// All rights reserved.

// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using System;
namespace ComponentAce.Compression.Libs.zlib
{

    public class ZInputStream : System.IO.BinaryReader
    {
        internal void InitBlock()
        {
            flush = zlibConst.Z_NO_FLUSH;
            buf = new byte[bufsize];
        }
        virtual public int FlushMode
        {
            get
            {
                return (flush);
            }

            set
            {
                this.flush = value;
            }

        }
        ///  Returns the total number of bytes input so far.
        virtual public long TotalIn
        {
            get
            {
                return z.total_in;
            }

        }
        ///  Returns the total number of bytes output so far.
        virtual public long TotalOut
        {
            get
            {
                return z.total_out;
            }

        }

        protected ZStream z = new ZStream();
        protected int bufsize = 512;
        protected int flush;
        protected byte[] buf, buf1 = new byte[1];
        protected bool compress;

        internal System.IO.Stream in_Renamed = null;

        public ZInputStream(System.IO.Stream in_Renamed) : base(in_Renamed)
        {
            InitBlock();
            this.in_Renamed = in_Renamed;
            z.inflateInit();
            compress = false;
            z.next_in = buf;
            z.next_in_index = 0;
            z.avail_in = 0;
        }

        public ZInputStream(System.IO.Stream in_Renamed, int level) : base(in_Renamed)
        {
            InitBlock();
            this.in_Renamed = in_Renamed;
            z.deflateInit(level);
            compress = true;
            z.next_in = buf;
            z.next_in_index = 0;
            z.avail_in = 0;
        }

        /*public int available() throws IOException {
		return inf.finished() ? 0 : 1;
		}*/

        public override int Read()
        {
            if (read(buf1, 0, 1) == -1)
                return (-1);
            return (buf1[0] & 0xFF);
        }

        internal bool nomoreinput = false;

        public int read(byte[] b, int off, int len)
        {
            if (len == 0)
                return (0);
            int err;
            z.next_out = b;
            z.next_out_index = off;
            z.avail_out = len;
            do
            {
                if ((z.avail_in == 0) && (!nomoreinput))
                {
                    // if buffer is empty and more input is avaiable, refill it
                    z.next_in_index = 0;
                    z.avail_in = SupportClass.ReadInput(in_Renamed, buf, 0, bufsize); //(bufsize<z.avail_out ? bufsize : z.avail_out));
                    if (z.avail_in == -1)
                    {
                        z.avail_in = 0;
                        nomoreinput = true;
                    }
                }
                if (compress)
                    err = z.deflate(flush);
                else
                    err = z.inflate(flush);
                if (nomoreinput && (err == zlibConst.Z_BUF_ERROR))
                    return (-1);
                if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
                    throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
                if (nomoreinput && (z.avail_out == len))
                    return (-1);
            }
            while (z.avail_out == len && err == zlibConst.Z_OK);
            //System.err.print("("+(len-z.avail_out)+")");
            return (len - z.avail_out);
        }

        public long skip(long n)
        {
            int len = 512;
            if (n < len)
                len = (int)n;
            byte[] tmp = new byte[len];
            return ((long)SupportClass.ReadInput(BaseStream, tmp, 0, tmp.Length));
        }
    }
}


text:
				Você está em: Página Inicial

				Comissão Distrital

		A Comissão

Equipe do 35º Distrito Escoteiro

{{member.name}}

{{member.function}}

{{member.email}}


text:
package com.tuongky;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tuongky.backend.InviteDao;
import com.tuongky.model.datastore.Invite;
import com.tuongky.util.JsonUtils;

@SuppressWarnings("serial")
public class InviteCreateServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    InviteDao inviteDao = new InviteDao();
    Invite invite = inviteDao.save();
    resp.setContentType(Constants.CT_JSON);
    resp.getWriter().println(JsonUtils.toJson("inviteId", invite.getId()));
  }
}


text:
package io.lucci.springwalkthrough.todoapi.persistence.entity;

public class TaskEntity {

}


text:
package daemon

import (
	"encoding/json"
	"fmt"
	"sort"
	"time"

	"github.com/pkg/errors"

	"github.com/docker/distribution/reference"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/container"
	"github.com/docker/docker/image"
	"github.com/docker/docker/layer"
)

var acceptedImageFilterTags = map[string]bool{
	"dangling":  true,
	"label":     true,
	"before":    true,
	"since":     true,
	"reference": true,
}

// byCreated is a temporary type used to sort a list of images by creation
// time.
type byCreated []*types.ImageSummary

func (r byCreated) Len() int           { return len(r) }
func (r byCreated) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r byCreated) Less(i, j int) bool { return r[i].Created < r[j].Created }

// Map returns a map of all images in the ImageStore
func (daemon *Daemon) Map() map[image.ID]*image.Image {
	return daemon.imageStore.Map()
}

// Images returns a filtered list of images. filterArgs is a JSON-encoded set
// of filter arguments which will be interpreted by api/types/filters.
// filter is a shell glob string applied to repository names. The argument
// named all controls whether all images in the graph are filtered, or just
// the heads.
func (daemon *Daemon) Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) {
	var (
		allImages    map[image.ID]*image.Image
		err          error
		danglingOnly = false
	)

	if err := imageFilters.Validate(acceptedImageFilterTags); err != nil {
		return nil, err
	}

	if imageFilters.Include("dangling") {
		if imageFilters.ExactMatch("dangling", "true") {
			danglingOnly = true
		} else if !imageFilters.ExactMatch("dangling", "false") {
			return nil, fmt.Errorf("Invalid filter 'dangling=%s'", imageFilters.Get("dangling"))
		}
	}
	if danglingOnly {
		allImages = daemon.imageStore.Heads()
	} else {
		allImages = daemon.imageStore.Map()
	}

	var beforeFilter, sinceFilter *image.Image
	err = imageFilters.WalkValues("before", func(value string) error {
		beforeFilter, err = daemon.GetImage(value)
		return err
	})
	if err != nil {
		return nil, err
	}

	err = imageFilters.WalkValues("since", func(value string) error {
		sinceFilter, err = daemon.GetImage(value)
		return err
	})
	if err != nil {
		return nil, err
	}

	images := []*types.ImageSummary{}
	var imagesMap map[*image.Image]*types.ImageSummary
	var layerRefs map[layer.ChainID]int
	var allLayers map[layer.ChainID]layer.Layer
	var allContainers []*container.Container

	for id, img := range allImages {
		if beforeFilter != nil {
			if img.Created.Equal(beforeFilter.Created) || img.Created.After(beforeFilter.Created) {
				continue
			}
		}

		if sinceFilter != nil {
			if img.Created.Equal(sinceFilter.Created) || img.Created.Before(sinceFilter.Created) {
				continue
			}
		}

		if imageFilters.Include("label") {
			// Very old image that do not have image.Config (or even labels)
			if img.Config == nil {
				continue
			}
			// We are now sure image.Config is not nil
			if !imageFilters.MatchKVList("label", img.Config.Labels) {
				continue
			}
		}

		layerID := img.RootFS.ChainID()
		var size int64
		if layerID != "" {
			l, err := daemon.layerStore.Get(layerID)
			if err != nil {
				return nil, err
			}

			size, err = l.Size()
			layer.ReleaseAndLog(daemon.layerStore, l)
			if err != nil {
				return nil, err
			}
		}

		newImage := newImage(img, size)

		for _, ref := range daemon.referenceStore.References(id.Digest()) {
			if imageFilters.Include("reference") {
				var found bool
				var matchErr error
				for _, pattern := range imageFilters.Get("reference") {
					found, matchErr = reference.FamiliarMatch(pattern, ref)
					if matchErr != nil {
						return nil, matchErr
					}
				}
				if !found {
					continue
				}
			}
			if _, ok := ref.(reference.Canonical); ok {
				newImage.RepoDigests = append(newImage.RepoDigests, reference.FamiliarString(ref))
			}
			if _, ok := ref.(reference.NamedTagged); ok {
				newImage.RepoTags = append(newImage.RepoTags, reference.FamiliarString(ref))
			}
		}
		if newImage.RepoDigests == nil && newImage.RepoTags == nil {
			if all || len(daemon.imageStore.Children(id)) == 0 {

				if imageFilters.Include("dangling") && !danglingOnly {
					//dangling=false case, so dangling image is not needed
					continue
				}
				if imageFilters.Include("reference") { // skip images with no references if filtering by reference
					continue
				}
				newImage.RepoDigests = []string{"<none>@<none>"}
				newImage.RepoTags = []string{"<none>:<none>"}
			} else {
				continue
			}
		} else if danglingOnly && len(newImage.RepoTags) > 0 {
			continue
		}

		if withExtraAttrs {
			// lazily init variables
			if imagesMap == nil {
				allContainers = daemon.List()
				allLayers = daemon.layerStore.Map()
				imagesMap = make(map[*image.Image]*types.ImageSummary)
				layerRefs = make(map[layer.ChainID]int)
			}

			// Get container count
			newImage.Containers = 0
			for _, c := range allContainers {
				if c.ImageID == id {
					newImage.Containers++
				}
			}

			// count layer references
			rootFS := *img.RootFS
			rootFS.DiffIDs = nil
			for _, id := range img.RootFS.DiffIDs {
				rootFS.Append(id)
				chid := rootFS.ChainID()
				layerRefs[chid]++
				if _, ok := allLayers[chid]; !ok {
					return nil, fmt.Errorf("layer %v was not found (corruption?)", chid)
				}
			}
			imagesMap[img] = newImage
		}

		images = append(images, newImage)
	}

	if withExtraAttrs {
		// Get Shared sizes
		for img, newImage := range imagesMap {
			rootFS := *img.RootFS
			rootFS.DiffIDs = nil

			newImage.SharedSize = 0
			for _, id := range img.RootFS.DiffIDs {
				rootFS.Append(id)
				chid := rootFS.ChainID()

				diffSize, err := allLayers[chid].DiffSize()
				if err != nil {
					return nil, err
				}

				if layerRefs[chid] > 1 {
					newImage.SharedSize += diffSize
				}
			}
		}
	}

	sort.Sort(sort.Reverse(byCreated(images)))

	return images, nil
}

// SquashImage creates a new image with the diff of the specified image and the specified parent.
// This new image contains only the layers from it's parent + 1 extra layer which contains the diff of all the layers in between.
// The existing image(s) is not destroyed.
// If no parent is specified, a new image with the diff of all the specified image's layers merged into a new layer that has no parents.
func (daemon *Daemon) SquashImage(id, parent string) (string, error) {
	img, err := daemon.imageStore.Get(image.ID(id))
	if err != nil {
		return "", err
	}

	var parentImg *image.Image
	var parentChainID layer.ChainID
	if len(parent) != 0 {
		parentImg, err = daemon.imageStore.Get(image.ID(parent))
		if err != nil {
			return "", errors.Wrap(err, "error getting specified parent layer")
		}
		parentChainID = parentImg.RootFS.ChainID()
	} else {
		rootFS := image.NewRootFS()
		parentImg = &image.Image{RootFS: rootFS}
	}

	l, err := daemon.layerStore.Get(img.RootFS.ChainID())
	if err != nil {
		return "", errors.Wrap(err, "error getting image layer")
	}
	defer daemon.layerStore.Release(l)

	ts, err := l.TarStreamFrom(parentChainID)
	if err != nil {
		return "", errors.Wrapf(err, "error getting tar stream to parent")
	}
	defer ts.Close()

	newL, err := daemon.layerStore.Register(ts, parentChainID)
	if err != nil {
		return "", errors.Wrap(err, "error registering layer")
	}
	defer daemon.layerStore.Release(newL)

	var newImage image.Image
	newImage = *img
	newImage.RootFS = nil

	var rootFS image.RootFS
	rootFS = *parentImg.RootFS
	rootFS.DiffIDs = append(rootFS.DiffIDs, newL.DiffID())
	newImage.RootFS = &rootFS

	for i, hi := range newImage.History {
		if i >= len(parentImg.History) {
			hi.EmptyLayer = true
		}
		newImage.History[i] = hi
	}

	now := time.Now()
	var historyComment string
	if len(parent) > 0 {
		historyComment = fmt.Sprintf("merge %s to %s", id, parent)
	} else {
		historyComment = fmt.Sprintf("create new from %s", id)
	}

	newImage.History = append(newImage.History, image.History{
		Created: now,
		Comment: historyComment,
	})
	newImage.Created = now

	b, err := json.Marshal(&newImage)
	if err != nil {
		return "", errors.Wrap(err, "error marshalling image config")
	}

	newImgID, err := daemon.imageStore.Create(b)
	if err != nil {
		return "", errors.Wrap(err, "error creating new image after squash")
	}
	return string(newImgID), nil
}

func newImage(image *image.Image, size int64) *types.ImageSummary {
	newImage := new(types.ImageSummary)
	newImage.ParentID = image.Parent.String()
	newImage.ID = image.ID().String()
	newImage.Created = image.Created.Unix()
	newImage.Size = size
	newImage.VirtualSize = size
	newImage.SharedSize = -1
	newImage.Containers = -1
	if image.Config != nil {
		newImage.Labels = image.Config.Labels
	}
	return newImage
}


text:
import qml
import numpy as np
import os
import sys

from qml.wrappers import arad_local_kernels, arad_local_symmetric_kernels

def get_energies(filename):
    """ Returns a dictionary with heats of formation for each xyz-file.
    """

    f = open(filename, "r")
    lines = f.readlines()
    f.close()

    energies = dict()

    for line in lines:
        tokens = line.split()

        xyz_name = tokens[0]
        hof = float(tokens[1])

        energies[xyz_name] = hof

    return energies

# def test_arad_wrapper():
#
#     test_dir = os.path.dirname(os.path.realpath(__file__))
#
#     # Parse file containing PBE0/def2-TZVP heats of formation and xyz filenames
#     data = get_energies("%s/data/hof_qm7.txt" % test_dir)
#
#     # Generate a list of qml.Compound() objects
#     mols = []
#
#     for xyz_file in sorted(data.keys())[:50]:
#
#         # Initialize the qml.Compound() objects
#         mol = qml.Compound(xyz="%s/qm7/" % test_dir + xyz_file)
#
#         # Associate a property (heat of formation) with the object
#         mol.properties = data[xyz_file]
#
#         # This is a Molecular Coulomb matrix sorted by row norm
#         mol.generate_arad_representation(size=23)
#
#         mols.append(mol)
#
#
#     # Shuffle molecules
#     np.random.seed(666)
#     np.random.shuffle(mols)
#
#     # Make training and test sets
#     n_test  = 10
#     n_train = 40
#
#     training = mols[:n_train]
#     test  = mols[-n_test:]
#
#     sigmas = [10.0, 100.0]
#
#
#     K1 = arad_local_symmetric_kernels(training, sigmas)
#     assert np.all(K1 > 0.0), "ERROR: ARAD symmetric kernel negative"
#     assert np.invert(np.all(np.isnan(K1))), "ERROR: ARAD symmetric kernel contains NaN"
#
#
#     K2 = arad_local_kernels(training, test, sigmas)
#     assert np.all(K2 > 0.0), "ERROR: ARAD symmetric kernel negative"
#     assert np.invert(np.all(np.isnan(K2))), "ERROR: ARAD symmetric kernel contains NaN"

if __name__ == "__main__":

    pass
    # test_arad_wrapper()


text:
"""
@@
"""
from __future__ import print_function

import sys
import screed
import khmer
from khmer.khmer_args import build_counting_args, DEFAULT_MAX_TABLESIZE

DEFAULT_LOWER_CUTOFF = 2000
DEFAULT_UPPER_CUTOFF = 65535

###

def main():
    parser = build_construct_args()
    parser.add_argument('-l', '--lower-cutoff', type=int, dest='lower_cutoff',
                        default=DEFAULT_LOWER_CUTOFF)
    parser.add_argument('-u', '--upper-cutoff', type=int, dest='upper_cutoff',
                        default=DEFAULT_UPPER_CUTOFF)

    parser.add_argument('output_filename')
    parser.add_argument('input_filename')

    args = parser.parse_args()

    if not args.quiet:
        if args.min_hashsize == DEFAULT_MAX_TABLESIZE:
            print("** WARNING: hashsize is default!  " \
                "You absodefly want to increase this!\n** " \
                "Please read the docs!", file=sys.stderr)

        print('\nPARAMETERS:', file=sys.stderr)
        print(' - kmer size =    %d \t\t(-k)' % args.ksize, file=sys.stderr)
        print(' - n hashes =     %d \t\t(-N)' % args.n_hashes, file=sys.stderr)
        print(' - min hashsize = %-5.2g \t(-x)' % \
            args.min_hashsize, file=sys.stderr)
        print('', file=sys.stderr)
        print('Estimated memory usage is %.2g bytes " \
            "(n_hashes x min_hashsize)' % (
            args.n_hashes * args.min_hashsize), file=sys.stderr)
        print('-' * 8, file=sys.stderr)

    K = args.ksize
    HT_SIZE = args.min_hashsize
    N_HT = args.n_hashes

    output = args.output_filename
    input = args.input_filename

    print('lower cutoff:', args.lower_cutoff)
    print('upper cutoff:', args.upper_cutoff)
    print('Saving stoptags to %s' % output)
    print('Loading sequences in %s' % input)

    ###

    print('making hashtable')
    ht = khmer.CountingHash(K, HT_SIZE, N_HT)
    ht.set_use_bigcount(True)

    print('consuming input', input)
    hb = ht.collect_high_abundance_kmers(input,
                                         args.lower_cutoff,
                                         args.upper_cutoff)

    print('saving stoptags', output)
    hb.save_stop_tags(output)

if __name__ == '__main__':
    main()

# vim: set ft=python ts=4 sts=4 sw=4 et tw=79:


text:
<?php

/**
 * Performs a query on the database
 *
 * @phpstub
 *
 * @param resource $link
 * @param string $query
 *
 * @return bool
 */
function maxdb_multi_query($link, $query)
{
}

/**
 * Performs a query on the database
 *
 * @phpstub
 *
 * @param string $query
 *
 * @return bool
 */
function maxdb_multi_query($query)
{
}


text:
from pymtl        import *
from pclib.ifcs import InValRdyBundle, OutValRdyBundle

from GreenletWrapper  import GreenletWrapper
from ListMemPortProxy import ListMemPortProxy

#-------------------------------------------------------------------------
# Function Implementation
#-------------------------------------------------------------------------
# This is a plain function implementation of the desired vector-vector
# add behavior.

def vvadd( dest, src0, src1 ):

  for i in xrange(len(dest)):
    dest[i] = src0[i] + src1[i]

#-------------------------------------------------------------------------
# Port-Based Wrapper
#-------------------------------------------------------------------------
# We can use greenlets to wrap the plain function implementation so that
# it can correctly interact with the split-phase memory interface.

class VVAddUnitGBL (Model):

  #-----------------------------------------------------------------------
  # Constructor
  #-----------------------------------------------------------------------

  def __init__( s, memreq_params, memresp_params,
                dest_addr, src0_addr, src1_addr, size ):

    # Short names

    mreq_p  = memreq_params
    mresp_p = memresp_params

    # Memory request/response ports

    s.memreq  = InValRdyBundle  ( mreq_p.nbits  )
    s.memresp = OutValRdyBundle ( mresp_p.nbits )

    # ListMemPortProxy objects

    L = ListMemPortProxy
    s.dest = L( mreq_p, mresp_p, dest_addr, size, s.memreq, s.memresp )
    s.src0 = L( mreq_p, mresp_p, src0_addr, size, s.memreq, s.memresp )
    s.src1 = L( mreq_p, mresp_p, src1_addr, size, s.memreq, s.memresp )

    # Greenlet for functional implementation

    s.vvadd = GreenletWrapper(vvadd)

  #-----------------------------------------------------------------------
  # elaborate_logic
  #-----------------------------------------------------------------------

  def elaborate_logic( s ):

    @s.tick
    def logic():

      # This looks like a plain function call, but the greenlets mean
      # that something more sophisticated is going on. The first time we
      # call this wrapper function, the underlying vvadd function will
      # try and access the src0 list. This will get proxied to the dest
      # ListMemPortProxy object which will create a memory request and
      # send it out the memreq port. Since we do not have the data yet,
      # we cannot return the data to the underlying vvadd function so
      # instead we use greenlets to switch back to the tick function. If
      # we had code after this it would be executed. The next time we
      # call tick, we call the wrapper function again, and essentially we
      # jump back into the ListMemPortProxy to see if the response had
      # returned. When the response eventually returns, the
      # ListMemPortProxy object will return the data and the underlying
      # vvadd function will move onto src1.

      s.vvadd( s.dest, s.src0, s.src1 )

  #-----------------------------------------------------------------------
  # done
  #-----------------------------------------------------------------------

  def done( s ):

    # GreenletWrapper objects include a done method which indicates when
    # they underlying vvadd function has completely finished its
    # execution.

    return s.vvadd.done()

  #-----------------------------------------------------------------------
  # line_trace
  #-----------------------------------------------------------------------

  def line_trace( s ):
    return s.dest.line_trace() + " " + \
           s.src0.line_trace() + " " + \
           s.src1.line_trace()


text:
{% extends 'base.html' %}

{% block page_title %} Edit: {{ place.name }} {% endblock %}

{% block extra_head %}
    <link rel="stylesheet" href="/static/select2/select2.css" />

{% endblock %}

{% block content %}

Edit {{ place.name }}

<form id="placeForm">

ID: {{ place.id }}

Name: <input id="placeName" value="{{ place.name }}" type="text" />

            Feature Code:
            <input type="hidden" class="select2autocomplete" style="width:400px;height:20px;" id="featureCode" value="{{ place.feature_code }}" />

<input type="submit" value="Save" />

</form>

{% endblock %}


text:
<resources>
    <string name="app_name">Muscle Prime</string>

    <string name="title_Treinos">Treinos</string>
    <string name="title_NovoTreino">Novo Treino</string>
    <string name="title_AdicionaExercicios">Exercícios</string>
    <string name="title_Treinar">Iniciar atividade</string>
    <string name="title_LogTreinos">Log de treinos</string>
    <string name="title_Sobre">Sobre</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_example">NOVO</string>

    <string name="action_settings">Configurações</string>
</resources>


text:
package de.unioninvestment.eai.portal.support.vaadin.filter;

import java.text.MessageFormat;

import com.vaadin.data.Container.Filter;
import com.vaadin.data.util.sqlcontainer.query.generator.StatementHelper;
import com.vaadin.data.util.sqlcontainer.query.generator.filter.FilterTranslator;
import com.vaadin.data.util.sqlcontainer.query.generator.filter.QueryBuilder;

/**
 * A Vaadin SQLContainer filter translator for {@link DatabaseRegExpFilter}.
 *
 * @author carsten.mjartan
 *
 */
public class MySQLRegExpFilterTranslator implements FilterTranslator {

	private static final long serialVersionUID = 1L;

	@Override
	public boolean translatesFilter(Filter filter) {
		return filter instanceof DatabaseRegExpFilter;
	}

	@Override
	public String getWhereStringForFilter(Filter filter, StatementHelper sh) {

		DatabaseRegExpFilter regexpFilter = (DatabaseRegExpFilter) filter;
		if (regexpFilter.getMatchParameter() != null) {
			throw new IllegalArgumentException("Modifiers are not supported by MySQL REGEXP");
		}

		String columnName = QueryBuilder.quote(regexpFilter.getColumn());
		sh.addParameterValue(regexpFilter.getPattern());

		return MessageFormat.format("{0} REGEXP ?", columnName);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 日历控件属性 -->
    <declare-styleable name="DayPickerView">
        <attr name="colorCurrentDay" format="color"/>
        <attr name="colorSelectedDayBackground" format="color"/>
        <attr name="colorSelectedDayText" format="color"/>
        <attr name="colorPreviousDay" format="color"/>
        <attr name="colorNormalDay" format="color" />
        <attr name="colorMonthName" format="color" />
        <attr name="colorMonthBackground" format="color" />
        <attr name="colorDayName" format="color" />
        <attr name="textSizeDay" format="dimension"/>
        <attr name="textSizeMonth" format="dimension" />
        <attr name="textSizeDayName" format="dimension" />
        <attr name="textSizeInfo" format="dimension" />
        <attr name="headerMonthHeight" format="dimension" />
        <!--<attr name="selectedDayRadius" format="dimension" />-->
        <attr name="calendarHeight" format="dimension" />
        <attr name="calendarDayHeight" format="dimension" />
        <attr name="enablePreviousDay" format="boolean" />
        <attr name="currentDaySelected" format="boolean" />
        <attr name="drawRoundRect" format="boolean" />
        <attr name="showMonthCount" format="integer" />
        <attr name="colorWeekend" format="color" />
        <attr name="colorLink" format="color"/>
        <attr name="textStartStr" format="string" />
        <attr name="textEndStr" format="string"/>
        <attr name="textWeekend" format="string"/><!--周末如果显示什么字为上班的标示-->
        <attr name="selectTextToTop" format="dimension" />
        <attr name="canSelectBeforeOneToday" format="boolean"/>
        <attr name="selectPointR" format="dimension"/><!--选择的圆的半径-->
        <attr name="colorSelectPoint" format="color"/>
        <attr name="selectLinkSize" format="dimension"/>
        <attr name="selectPadding" format="dimension"/><!--选择框的上下间距-->
        <attr name="selectPaddingLeftRigt" format="dimension"/><!--选择框的左右间距-->
        <attr name="colorSelectLink" format="color"/>
        <attr name="firstMonth" format="enum">
            <enum name="january" value="0" />
            <enum name="february" value="1" />
            <enum name="march" value="2" />
            <enum name="april" value="3" />
            <enum name="may" value="4" />
            <enum name="june" value="5" />
            <enum name="july" value="6" />
            <enum name="august" value="7" />
            <enum name="september" value="8" />
            <enum name="october" value="9" />
            <enum name="november" value="10" />
            <enum name="december" value="11" />
        </attr>
        <attr name="lastMonth" format="enum">
            <enum name="january" value="0" />
            <enum name="february" value="1" />
            <enum name="march" value="2" />
            <enum name="april" value="3" />
            <enum name="may" value="4" />
            <enum name="june" value="5" />
            <enum name="july" value="6" />
            <enum name="august" value="7" />
            <enum name="september" value="8" />
            <enum name="october" value="9" />
            <enum name="november" value="10" />
            <enum name="december" value="11" />
        </attr>
    </declare-styleable>
    <!--双向seekBar-->
    <declare-styleable name="SeekBarPressure">
        <attr name="minValue" format="float" />
        <attr name="maxValue" format="float" />
        <attr name="duration" format="float" />
        <attr name="lwidth" format="dimension">
            <enum name="fill_parent" value="-1" />
            <enum name="match_parent" value="-1" />
            <enum name="wrap_content" value="-2" />
        </attr>
        <attr name="lheight" format="dimension">
            <enum name="fill_parent" value="-1" />
            <enum name="match_parent" value="-1" />
            <enum name="wrap_content" value="-2" />
        </attr>
        <attr name="circleRadius" format="dimension" />
    </declare-styleable>
</resources>


text:
#ifndef __DRIVER_COMM__
#define __DRIVER_COMM__

int read_int32(char **data);

/* Command strings will be two characters long */
/* and must be freed via driver_free()         */
char *read_command(char **data);

/* Any string read with this function must be */
/* freed with driver_free()                   */
char *read_string(char **data);

#endif


text:
layout: page
title: Landry Champion Tech Party
date: 2016-05-24
author: Larry Mercer
tags: weekly links, java
status: published
summary: Class aptent taciti sociosqu ad litora torquent.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/01/2017
  endDate: 04/02/2017
  ctyhocn: CHAKMHX
  groupCode: LCTP
published: true
---
Nullam sit amet tortor euismod, placerat erat eu, bibendum mi. Morbi at faucibus nunc, ut rutrum leo. Duis quis quam arcu. Integer pharetra nunc vulputate, iaculis tellus in, aliquam sem. Nunc blandit mauris dui, in varius lacus vulputate at. Mauris imperdiet dictum sapien, in ultrices nisi euismod vitae. Vestibulum dignissim, diam vel tincidunt cursus, nibh purus imperdiet libero, a lacinia orci tellus non sem. Fusce vitae velit quis neque accumsan maximus eget nec lacus. Curabitur quam lorem, fermentum blandit ultrices nec, molestie vel purus. Sed eget ligula ornare, dignissim risus at, tincidunt elit. Fusce mi enim, mattis nec malesuada sit amet, venenatis et risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In mi sapien, viverra id dignissim vitae, pretium a massa.

* Nulla ac augue ac risus ornare cursus in sed mauris
* Nulla tincidunt purus congue, venenatis magna eget, faucibus leo
* Nam eget magna in metus luctus dictum et tempus eros.

In tempus pharetra diam, et posuere ex mattis sed. Suspendisse sollicitudin finibus imperdiet. Morbi ex nunc, viverra ut ligula at, tristique semper nulla. Sed ultrices dui leo, sed ornare dui consequat at. In euismod molestie dolor vel ullamcorper. In hac habitasse platea dictumst. Vivamus sapien sem, sodales ac consectetur id, placerat non dui. Nam quis massa suscipit lorem finibus consectetur. Phasellus id ornare massa. Nam sed finibus est.