text:
package org.apache.oodt.cas.filemgr.tools;

import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.util.BytesRef;
import org.apache.oodt.cas.filemgr.structs.Element;
import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.ProductType;
import org.apache.oodt.cas.filemgr.structs.RangeQueryCriteria;
import org.apache.oodt.cas.filemgr.structs.TermQueryCriteria;
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.filemgr.structs.exceptions.RepositoryManagerException;
import org.apache.oodt.cas.filemgr.structs.exceptions.ValidationLayerException;
import org.apache.oodt.cas.filemgr.system.XmlRpcFileManagerClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author woollard
 * @version $Revision$
 *
 * <p>
 * A command line-search tool for the File Manager.
 * </p>
 *
 */
public class CatalogSearch {
    private static Logger LOG = Logger.getLogger(CatalogSearch.class.getName());

    private static XmlRpcFileManagerClient client;

    private static String freeTextBlock = "__FREE__";

    private static String productFilter = "";

    public CatalogSearch() {
    }

    public static void PostQuery(
            org.apache.oodt.cas.filemgr.structs.Query casQuery) {
        Vector products = new Vector();
        try {
            products = (Vector) client.getProductTypes();
        } catch (RepositoryManagerException e) {
            System.out
                    .println("Error getting available product types from the File Manager.");
            LOG.log(Level.SEVERE, e.getMessage());
        }
        for (Object product : products) {
            PostQuery(((ProductType) product).getProductTypeId(),
                casQuery);
        }
    }

    public static void PostQuery(String product,
            org.apache.oodt.cas.filemgr.structs.Query casQuery) {
        Vector results = new Vector();
        ProductType productType = null;

        try {
            productType = client.getProductTypeById(product);
        } catch (RepositoryManagerException e) {
            System.out.println("Could not access Product Type information");
            System.exit(-1);
        }

        try {
            results = (Vector) client.query(casQuery, productType);
        } catch (CatalogException ignore) {
            System.out.println("Error querying the File Manager");
            LOG.log(Level.SEVERE, ignore.getMessage());
            System.exit(-1);
        }

        if (results.isEmpty()) {
            System.out.println("No Products Found Matching This Criteria.");
        } else {
            System.out.println("Products Matching Query");
            for (Object result : results) {
                System.out.print(((Product) result).getProductName()
                                 + "\t");
                System.out.println(((Product) result).getProductId());
            }
        }
    }

    public static void setFilter(String filter) {
        productFilter = filter;
        try {
            client.getProductTypeById(filter);
        } catch (RepositoryManagerException e) {
            System.out.println("No product found with ID: " + filter);
            productFilter = "";
        }
        if (!productFilter.equals("")) {
            System.out.println("Filtering for " + productFilter + " products.");
        }
    }

    public static void removeFilter() {
        productFilter = "";
    }

    public static void ListProducts() {
        Vector products = new Vector();
        try {
            products = (Vector) client.getProductTypes();
        } catch (RepositoryManagerException e) {
            System.out
                    .println("Error getting available product types from the File Manager.");
            LOG.log(Level.SEVERE, e.getMessage());
        }
        for (Object product : products) {
            System.out.print(((ProductType) product).getProductTypeId()
                             + "\t");
            System.out.println(((ProductType) product).getName());
        }
    }

    public static void listElements() {
        Vector products;
        try {
            products = (Vector) client.getProductTypes();
            for (Object product : products) {
                listElements(((ProductType) product).getProductTypeId());
            }
        } catch (RepositoryManagerException e) {
            System.out
                    .println("Error getting available product types from the File Manager.");
            LOG.log(Level.SEVERE, e.getMessage());
        }

    }

    public static void listElements(String prodID) {
        Vector elements = new Vector();
        ProductType type;

        try {
            type = client.getProductTypeById(prodID);
            elements = (Vector) client.getElementsByProductType(type);
        } catch (RepositoryManagerException e1) {
            System.out.println("Could not find a ProductType with the ID: "
                    + prodID);
        } catch (ValidationLayerException e) {
            // TODO Auto-generated catch block
            LOG.log(Level.SEVERE, e.getMessage());
        }

        for (Object element : elements) {
            Element e = (Element) element;
            System.out.print(e.getElementId() + "\t");
            System.out.println(e.getElementName());
        }
    }

    public static void printHelp() {
        String add_filter = "add filter [productType]\n";
        add_filter += "\tAdd a filter on query results to only return products\n";
        add_filter += "\tmatching the specified productType.";

        String remove_filter = "remove filter\n";
        remove_filter += "\tRemove filters on query results.";

        String get_products = "get products\n";
        get_products += "\tReturns all ProductTypeIDs known to the Repository.";

        String get_elements = "get elements\n";
        get_elements += "\tReturns all Elements known to the Validation Layer.";

        String get_elements_for_product = "get elements for [productType]\n";
        get_elements_for_product += "\tReturns all Elements known to the ";
        get_elements_for_product += "Validation Layer\n\tfor the specified ";
        get_elements_for_product += "productType.";

        String query = "query [query]\n";
        query += "\tQueries the Catalog for all products matching the \n";
        query += "\tspecified query. If the filter is set, only products\n";
        query += "\tmatching the productType set in the filter will be\n";
        query += "\treturned. More details about query syntax can be found\n";
        query += "\tat http://lucene.apache.org/java/docs/queryparsersyntax.html";

        String quit = "quit\n";
        quit += "\tExits the program.";

        System.out.println("Available Commands:");
        System.out.println(add_filter);
        System.out.println(remove_filter);
        System.out.println(get_products);
        System.out.println(get_elements);
        System.out.println(get_elements_for_product);
        System.out.println(query);
        System.out.println(quit);
    }

    public static Query ParseQuery(String query) {
        // note that "__FREE__" is a control work for free text searching
        QueryParser parser = new QueryParser(freeTextBlock, new CASAnalyzer());
        Query luceneQ = null;
        try {
            luceneQ = (Query) parser.parse(query);
        } catch (ParseException e) {
            System.out.println("Error parsing query text.");
            System.exit(-1);
        }
        return luceneQ;
    }

    public static void GenerateCASQuery(
            org.apache.oodt.cas.filemgr.structs.Query casQuery,
            Query luceneQuery) {
        if (luceneQuery instanceof TermQuery) {
            Term t = ((TermQuery) luceneQuery).getTerm();
            if (!t.field().equals(freeTextBlock)) {
                casQuery
                        .addCriterion(new TermQueryCriteria(t.field(), t.text()));
            }
        } else if (luceneQuery instanceof PhraseQuery) {
            Term[] t = ((PhraseQuery) luceneQuery).getTerms();
            if (!t[0].field().equals(freeTextBlock)) {
                for (Term aT : t) {
                    casQuery.addCriterion(new TermQueryCriteria(aT.field(),
                        aT.text()));
                }
            }
        } else if (luceneQuery instanceof TermRangeQuery) {
            BytesRef startT = ((TermRangeQuery) luceneQuery).getLowerTerm();
            BytesRef endT = ((TermRangeQuery) luceneQuery).getUpperTerm();

            //TODO CHECK THIS RANGE!
            casQuery.addCriterion(new RangeQueryCriteria(((TermRangeQuery) luceneQuery).getField(), startT.utf8ToString(), endT.utf8ToString()));
        } else if (luceneQuery instanceof BooleanQuery) {
            List<BooleanClause> clauses = ((BooleanQuery) luceneQuery).clauses();
            for (BooleanClause clause : clauses) {
                GenerateCASQuery(casQuery, (clause).getQuery());
            }
        } else {
            System.out.println("Error Parsing Query");
            System.exit(-1);
        }
    }

    public static void CommandParser(String command) {
        StringTokenizer tok = new StringTokenizer(command, " ");
        int tokCount = tok.countTokens();

        if (tokCount > 0) {
            String com = tok.nextToken();
            if (com.equalsIgnoreCase("get")) {
                if (tokCount > 1) {
                    String subcom = tok.nextToken();
                    if (subcom.equalsIgnoreCase("products")) {
                        ListProducts();
                    } else if (subcom.equalsIgnoreCase("elements")) {
                        if (tokCount == 4
                                && tok.nextToken().equalsIgnoreCase("for")) {
                            String prodElements = tok.nextToken();
                            listElements(prodElements);
                        } else {
                            if (tokCount == 2) {
                                listElements();
                            } else {
                                System.out.println("Error parsing command");
                            }
                        }
                    }
                } else {
                    System.out.println("Error parsing command");
                }
            } else if (com.equalsIgnoreCase("add")) {
                if (tokCount == 3 && tok.nextToken().equalsIgnoreCase("filter")) {
                    setFilter(tok.nextToken());
                } else {
                    System.out.println("Error parsing command");
                }
            } else if (com.equalsIgnoreCase("remove")) {
                if (tokCount == 2 && tok.nextToken().equalsIgnoreCase("filter")) {
                    removeFilter();
                } else {
                    System.out.println("Error parsing command");
                }
            } else if (com.equalsIgnoreCase("help")) {
                printHelp();
            } else if (com.equalsIgnoreCase("exit")
                    || com.equalsIgnoreCase("quit")) {
                System.out.println("Exiting...");
                System.exit(0);
            } else if (com.equalsIgnoreCase("query")) {
                StringBuilder query = new StringBuilder();
                while (tok.hasMoreTokens()) {
                    query.append(tok.nextToken()).append(" ");
                }
                System.out.println("querying for: " + query);
                Query parsedQuery = ParseQuery(query.toString());
                org.apache.oodt.cas.filemgr.structs.Query casQuery = new org.apache.oodt.cas.filemgr.structs.Query();

                GenerateCASQuery(casQuery, parsedQuery);
                PostQuery(productFilter, casQuery);
            }
        }
    }

    public static void main(String[] args) {

        String fileManagerUrl = null;
        String welcomeMessage = "CatalogSearch v0.1\n";
        welcomeMessage += "Copyright 2006. California Institute of Technology.\n";
        String usage = "CatalogSearch --url <url to File Manager service>\n";
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // determine url
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("--url")) {
                fileManagerUrl = args[++i];
            }
        }

        if (fileManagerUrl == null) {
            System.err.println(usage);
            System.exit(1);
        }

        // connect with Filemgr Client
        boolean clientConnect = true;
        try {
            client = new XmlRpcFileManagerClient(new URL(fileManagerUrl));
        } catch (Exception e) {
            System.out
                    .println("Exception when communicating with file manager, errors to follow: message: "
                            + e.getMessage());
            clientConnect = false;
        }

        if (clientConnect) {

            System.out.println(welcomeMessage);

            String command;

            for (;;) {
                System.out.print("CatalogSearch>");

                try {
                    command = in.readLine();
                    CommandParser(command);

                } catch (IOException e) {
                    System.out.println("\nError Reading Query\n");
                    System.exit(-1);
                }
            }
        }
    }

}


text:
var modal = document.getElementById('shopsModal');

// Get the button that opens the modal
var btn1 = document.getElementById("modalTrigger");
//Extra button in the footer
var btn2 =document.getElementById("modalTrigger2");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn1.onclick = function() {
    modal.style.display = "block";
}
btn2.onclick = function() {
    modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
//bxslider library usage for responsive slider
//bxSlider
$(document).ready(function(){
  $('.bxslider').bxSlider({
    mode:'fade',
    speed:400,
    pagerCustom: '#bx-pager',
    controls: true,
    infiniteLoop: false,
    hideControlOnEnd: true,
  });

});

redpajama_set_name: RedPajamaGithub


text:
require_relative '../../test_helper'
require_relative 'flow_test_helper'
require 'gds_api/test_helpers/worldwide'

class RegisterABirthTest < ActiveSupport::TestCase
  include FlowTestHelper
  include GdsApi::TestHelpers::Worldwide

  setup do
    @location_slugs = %w(afghanistan andorra australia barbados belize cameroon central-african-republic china el-salvador estonia guatemala grenada hong-kong indonesia ireland iran laos libya maldives netherlands pakistan serbia spain sri-lanka st-kitts-and-nevis sweden taiwan thailand turkey united-arab-emirates usa vietnam yemen)
    worldwide_api_has_locations(@location_slugs)
    setup_for_testing_flow 'register-a-birth'
  end

  setup do
    setup_for_testing_flow 'register-a-birth'
  end

  should "ask which country the child was born in" do
    assert_current_node :country_of_birth?
  end

  context "answer Turkey" do
    setup do
      worldwide_api_has_organisations_for_location('turkey', read_fixture_file('worldwide/turkey_organisations.json'))
      add_response 'turkey'
    end
    should "ask which parent has british nationality" do
      assert_current_node :who_has_british_nationality?
    end
    context "answer mother" do
      setup do
        add_response 'mother'
      end
      should "ask if you are married or civil partnered" do
        assert_current_node :married_couple_or_civil_partnership?
      end
      context "answer no" do
        setup do
          add_response 'no'
        end
        should "ask where you are now and go to embassy result" do
          add_response "same_country"
          assert_current_node :embassy_result
        end
      end # not married/cp
    end # mother
  end # Turkey

  context "answer with a commonwealth country" do
    should "give the commonwealth result" do
      add_response 'australia'
      assert_current_node :commonwealth_result
    end
  end # commonweath result

  context "answer Andorra" do
    should "store the correct registration country" do
      worldwide_api_has_organisations_for_location('spain', read_fixture_file('worldwide/spain_organisations.json'))
      add_response 'andorra'
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_state_variable :registration_country, 'spain'
    end
  end # Andorra

  context "answer Iran" do
    should "give the no embassy outcome and be done" do
      worldwide_api_has_organisations_for_location('iran', read_fixture_file('worldwide/iran_organisations.json'))
      add_response 'iran'
      assert_current_node :no_embassy_result
    end
  end # Iran

  context "answer Spain" do
    setup do
      worldwide_api_has_organisations_for_location('spain', read_fixture_file('worldwide/spain_organisations.json'))
      add_response 'spain'
    end
    should "store this as the registration country" do
      assert_state_variable :registration_country, 'spain'
    end
    should "ask which parent has british nationality" do
      assert_current_node :who_has_british_nationality?
    end
    context "answer father" do
      setup do
        add_response 'father'
      end
      should "ask if you are married or civil partnered" do
        assert_current_node :married_couple_or_civil_partnership?
      end
      context "answer no" do
        setup do
          add_response 'no'
        end
        should "ask when the child was born" do
          assert_current_node :childs_date_of_birth?
        end
        context "answer pre 1st July 2006" do
          should "give the homeoffice result" do
            add_response '2006-06-30'
            assert_current_node :homeoffice_result
          end
        end
        context "answer on or after 1st July 2006" do
          setup do
            add_response '2006-07-01'
          end
          should "ask where you are now" do
            assert_current_node :where_are_you_now?
          end
        end
      end # not married/cp
    end # father is british citizen
    context "answer mother and father" do
      setup do
        add_response 'mother_and_father'
      end
      should "ask if you are married or civil partnered" do
        assert_current_node :married_couple_or_civil_partnership?
      end
      context "answer yes" do
        setup do
          add_response 'yes'
        end
        should "ask where you are now" do
          assert_current_node :where_are_you_now?
        end
        context "answer back in the UK" do
          should "give the fco result" do
            add_response 'in_the_uk'
            assert_state_variable :registration_country, 'spain'
            assert_current_node :fco_result
            assert_phrase_list :birth_registration_form, [:birth_registration_form]
            assert_state_variable :embassy_high_commission_or_consulate, "British consulate general"
          end
        end
        context "answer in another country" do
          setup do
            add_response "another_country"
          end
          context "answer which country" do
            should "Ireland and get the commonwealth result" do
              worldwide_api_has_organisations_for_location('ireland', read_fixture_file('worldwide/ireland_organisations.json'))
              add_response 'ireland'
              assert_state_variable :another_country, true
              assert_state_variable :registration_country, 'ireland'
              assert_phrase_list :birth_registration_form, [:birth_registration_form]
              assert_current_node :embassy_result
            end # now in Ireland
            should "USA and get the embassy outcome" do
              worldwide_api_has_organisations_for_location('usa', read_fixture_file('worldwide/usa_organisations.json'))
              add_response 'usa'
              assert_state_variable :embassy_high_commission_or_consulate, "British embassy"
              assert_state_variable :registration_country, "usa"
              assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_all]
              assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
              assert_phrase_list :go_to_the_embassy, [:registering_clickbook, :registering_either_parent]
              assert_state_variable :clickbook_data, 'http://www.britishembassydc.clickbook.net/'
              assert_state_variable :postal_form_url, nil
              assert_phrase_list :postal, [:postal_info, :"postal_info_usa"]
              assert_phrase_list :footnote, [:footnote_another_country]
              assert_current_node :embassy_result
            end # now in USA
            should "answer Yemen and get the no embassy outcome" do
              add_response 'yemen'
              assert_current_node :no_embassy_result
              assert_state_variable :registration_country_name, "Yemen"
            end # now in Yemen
          end # in another country
        end # mother and father british citizens
      end # married
    end # Spain
  end
  context "answer Afghanistan" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('afghanistan', read_fixture_file('worldwide/afghanistan_organisations.json'))
      add_response "afghanistan"
      add_response "mother_and_father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :embassy_high_commission_or_consulate, "British embassy"
      assert_state_variable :registration_country_name, "Afghanistan"
      assert_state_variable :british_national_parent, 'mother_and_father'
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_all]
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :go_to_the_embassy, [:registering_all, :registering_either_parent]
      assert_state_variable :postal_form_url, nil
      assert_state_variable :postal, ""
      assert_phrase_list :footnote, [:footnote_exceptions]
    end
  end # Afghanistan
  context "answer Pakistan" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('pakistan', read_fixture_file('worldwide/pakistan_organisations.json'))
      add_response "pakistan"
      add_response "father"
      add_response "yes"
      add_response "in_the_uk"
      assert_current_node :embassy_result
    end
  end # Pakistan
  context "answer Sweden" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('sweden', read_fixture_file('worldwide/sweden_organisations.json'))
      add_response "sweden"
      add_response "father"
      add_response "no"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'mother_and_father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_sweden]
      assert_phrase_list :documents_footnote, [:docs_footnote_sweden]
    end
  end # Sweden
  context "answer Taiwan" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('taiwan', read_fixture_file('worldwide/taiwan_organisations.json'))
      add_response "taiwan"
      add_response "mother_and_father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'mother_and_father'
      assert_state_variable :embassy_high_commission_or_consulate, 'British Trade & Cultural Office'
      assert_phrase_list :cash_only, [:cheque_only]
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_taiwan]
    end
  end # Taiwan
  context "answer Taiwan now in the UK" do
    should "give the FCO result" do
      add_response "taiwan"
      add_response "mother_and_father"
      add_response "yes"
      add_response "in_the_uk"
      assert_current_node :fco_result
      assert_state_variable :british_national_parent, 'mother_and_father'
    end
  end # Taiwan
  context "answer Central African Republic now in the UK" do
    should "give the FCO result" do
      add_response "central-african-republic"
      add_response "mother_and_father"
      add_response "yes"
      add_response "in_the_uk"
      assert_current_node :fco_result
      assert_state_variable :british_national_parent, 'mother_and_father'
    end
  end # Central African Republic
  context "answer Belize" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('belize', read_fixture_file('worldwide/belize_organisations.json'))
      add_response "belize"
      add_response "father"
      add_response "no"
      add_response "2006-07-01"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_all]
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :go_to_the_embassy, [:registering_clickbook, :registering_paternity_declaration]
    end # Not married or CP
  end # Belize
  context "answer Libya" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('libya', read_fixture_file('worldwide/libya_organisations.json'))
      add_response "libya"
      add_response "father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees_libya]
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_libya]
      assert_phrase_list :go_to_the_embassy, [:registering_all, :registering_either_parent]
    end # Not married or CP
  end # Libya
  context "answer Hong Kong" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('hong-kong', read_fixture_file('worldwide/hong-kong_organisations.json'))
      add_response "hong-kong"
      add_response "father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_all]
      assert_phrase_list :go_to_the_embassy, [:registering_hong_kong, :registering_either_parent]
    end # Not married or CP
  end # Hong Kong
  context "answer barbados" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('barbados', read_fixture_file('worldwide/barbados_organisations.json'))
      add_response "barbados"
      add_response "father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :documents_you_must_provide, [:documents_you_must_provide_all]
      assert_phrase_list :go_to_the_embassy, [:registering_all, :registering_either_parent]
      assert_state_variable :cash_only, ''
      assert_phrase_list :footnote, [:footnote]
    end # Not married or CP
  end # Barbados
  context "answer united arab emirates" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('united-arab-emirates', read_fixture_file('worldwide/united-arab-emirates_organisations.json'))
      add_response "united-arab-emirates"
      add_response "father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :documents_you_must_provide, [:"documents_you_must_provide_united-arab-emirates"]
      assert_state_variable :cash_only, ''
      assert_phrase_list :footnote, [:footnote]
      assert_match /British Embassy Dubai/, outcome_body # there are two separate organisations in UAE so this tests that the correct embassy (Dubai) is returned
    end # Not married or CP
  end # UAE
  context "answer indonesia" do
    should "give the embassy result" do
      worldwide_api_has_organisations_for_location('indonesia', read_fixture_file('worldwide/indonesia_organisations.json'))
      add_response "indonesia"
      add_response "father"
      add_response "no"
      add_response "2007-06-05"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :fees_for_consular_services, [:consular_service_fees]
      assert_phrase_list :embassy_result_indonesia_british_father_paternity, [:indonesia_british_father_paternity]
      assert_phrase_list :documents_you_must_provide, [:"documents_you_must_provide_all"]
      assert_state_variable :cash_only, ''
      assert_phrase_list :footnote, [:footnote]
    end # Not married or CP
  end # Indonesia

  context "el-salvador, where you have to register in guatemala" do
    setup do
      worldwide_api_has_organisations_for_location('guatemala', read_fixture_file('worldwide/guatemala_organisations.json'))
      add_response "el-salvador"
    end

    should "calculate the registration country as Guatemala" do
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_state_variable :registration_country, "guatemala"
      assert_state_variable :registration_country_name, "Guatemala"
    end
  end

  context "laos, no longer have to register in thailand" do
    setup do
      worldwide_api_has_organisations_for_location('laos', read_fixture_file('worldwide/laos_organisations.json'))
      add_response "laos"
    end
    should "calculate the registration country as Laos" do
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_state_variable :registration_country, "laos"
      assert_state_variable :registration_country_name, "Laos"
      assert_phrase_list :cash_only, [:cash_only]
    end
  end
  context "maldives, where you have to register in sri lanka" do
    setup do
      worldwide_api_has_organisations_for_location('sri-lanka', read_fixture_file('worldwide/sri-lanka_organisations.json'))
      add_response "maldives"
    end
    should "calculate the registration country as Sri Lanka" do
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_state_variable :registration_country, "sri-lanka"
      assert_state_variable :registration_country_name, "Sri Lanka"
    end
  end
  context "China" do
    should "render multiple clickbook links" do
      worldwide_api_has_organisations_for_location('china', read_fixture_file('worldwide/china_organisations.json'))
      add_response 'china'
      add_response 'mother'
      add_response 'yes'
      add_response 'same_country'
      assert_current_node :embassy_result
      assert outcome_body.at_css("ul li a[href='https://www.clickbook.net/dev/bc.nsf/sub/BritEmBeijing']")
    end
  end
  context "child born in grenada, parent in St kitts" do
    should "calculate the registration country as barbados" do
      worldwide_api_has_organisations_for_location('barbados', read_fixture_file('worldwide/barbados_organisations.json'))
      add_response 'grenada'
      add_response 'mother'
      add_response 'yes'
      add_response 'another_country'
      add_response 'st-kitts-and-nevis'
      assert_current_node :embassy_result
      assert_phrase_list :birth_registration_form, [:birth_registration_form]
    end
  end
  context "child born in usa, parent in usa" do
    should "give the embassy result with usa birth reg form" do
      worldwide_api_has_organisations_for_location('usa', read_fixture_file('worldwide/usa_organisations.json'))
      add_response 'usa'
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_current_node :embassy_result
      assert_phrase_list :birth_registration_form, [:birth_registration_form_usa]
    end
  end
  # testing for delivery return form in Spain
  context "child born in italy, parents in spain" do
    should "give the embassy result with italy delivery return form form" do
      worldwide_api_has_organisations_for_location('spain', read_fixture_file('worldwide/spain_organisations.json'))
      add_response 'spain'
      add_response 'mother_and_father'
      add_response 'yes'
      add_response 'same_country'
      assert_current_node :embassy_result
      assert_phrase_list :postal_return, [:postal_form_return]
      assert_phrase_list :birth_registration_form, [:birth_registration_form]
    end
  end
  context "answer Vietnam" do
    should "give the embassy result with Vietnam conditions" do
      worldwide_api_has_organisations_for_location('vietnam', read_fixture_file('worldwide/vietnam_organisations.json'))
      add_response 'vietnam'
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_current_node :embassy_result
      assert_phrase_list :postal, [:postal_form]
    end
  end # Vietnam
  context "answer Netherlands" do
    should "go to embassy result with modified card conditional" do
      worldwide_api_has_organisations_for_location('netherlands', read_fixture_file('worldwide/netherlands_organisations.json'))
      add_response 'netherlands'
      add_response 'father'
      add_response 'yes'
      add_response 'same_country'
      assert_current_node :embassy_result
      assert_phrase_list :postal, [:post_only_pay_by_card_countries]
    end
  end # Netherlands
    context "answer serbia" do
    should "check for clickbook and give embassy result" do
      worldwide_api_has_organisations_for_location('serbia', read_fixture_file('worldwide/serbia_organisations.json'))
      add_response "serbia"
      add_response "father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_state_variable :british_national_parent, 'father'
      assert_phrase_list :go_to_the_embassy, [:registering_clickbook, :registering_either_parent]
    end
  end # Serbia
    context "answer estonia" do
    should "show cash, credit card or cheque condition and give embassy result" do
      worldwide_api_has_organisations_for_location('estonia', read_fixture_file('worldwide/estonia_organisations.json'))
      add_response "estonia"
      add_response "mother_and_father"
      add_response "yes"
      add_response "same_country"
      assert_current_node :embassy_result
      assert_phrase_list :cash_only, [:cash_and_card]
    end
  end # Estonia
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>knife role — chef-client Man Pages</title>

    <link rel="stylesheet" href="_static/guide.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

knife role¶

A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run list are applied to the node’s configuration details. When a chef-client runs, it merges its own attributes and run lists with those contained within each assigned role.

The knife role subcommand is used to manage the roles that are associated with one or more nodes on a Chef server.

Note

To add a role to a node and then build out the run-list for that node, use the knife node sub-command and its <tt class="docutils literal">run_list add</tt> argument.

Note

Review the list of common options available to this (and all) Knife subcommands and plugins.

bulk delete¶

The <tt class="docutils literal">bulk delete</tt> argument is used to delete one or more roles that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/).

Syntax¶

This argument has the following syntax:

$ knife role bulk delete REGEX

Options¶

This command does not have any specific options.

Examples¶

The following examples show how to use this Knife subcommand:

Bulk delete roles

Use a regular expression to define the pattern used to bulk delete roles:

$ knife role bulk delete "^[0-9]{3}$"

create¶

The <tt class="docutils literal">create</tt> argument is used to add a role to the Chef server. Role data is saved as JSON on the Chef server.

Syntax¶

This argument has the following syntax:

$ knife role create ROLE_NAME (options)

Options¶

This argument has the following options:

<tt class="docutils literal">-d DESCRIPTION</tt>, <tt class="docutils literal">--description DESCRIPTION</tt>

The description of the role. This value will populate the description field for the role on the Chef server.

Examples¶

The following examples show how to use this Knife subcommand:

Create a role

To add a role named “role1”, enter:

$ knife role create role1

In the $EDITOR enter the role data in JSON:

## sample:
{
   "name": "role1",
   "default_attributes": {
   },
   "json_class": "Chef::Role",
   "run_list": ['recipe[cookbook_name::recipe_name],
                 role[role_name]'
   ],
   "description": "",
   "chef_type": "role",
   "override_attributes": {
   }
}

When finished, save it.

delete¶

The <tt class="docutils literal">delete</tt> argument is used to delete a role from the Chef server.

Syntax¶

This argument has the following syntax:

$ knife role delete ROLE_NAME

Options¶

This command does not have any specific options.

Examples¶

The following examples show how to use this Knife subcommand:

Delete a role

$ knife role delete devops

Type <tt class="docutils literal">Y</tt> to confirm a deletion.

edit¶

The <tt class="docutils literal">edit</tt> argument is used to edit role details on the Chef server.

Syntax¶

This argument has the following syntax:

$ knife role edit ROLE_NAME

Options¶

This command does not have any specific options.

Examples¶

The following examples show how to use this Knife subcommand:

Edit a role

To edit the data for a role named “role1”, enter:

$ knife role edit role1

Update the role data in JSON:

## sample:
{
   "name": "role1",
   "default_attributes": {
   },
   "json_class": "Chef::Role",
   "run_list": ['recipe[cookbook_name::recipe_name],
                 role[role_name]'
   ],
   "description": "This is the description for the role1 role.",
   "chef_type": "role",
   "override_attributes": {
   }
}

When finished, save it.

from file¶

The <tt class="docutils literal">from file</tt> argument is used to create a role using existing JSON data as a template.

Syntax¶

This argument has the following syntax:

$ knife role from file FILE

Options¶

This command does not have any specific options.

Examples¶

The following examples show how to use this Knife subcommand:

Create a role using JSON data

To view role details based on the values contained in a JSON file:

$ knife role from file "path to JSON file"

list¶

The <tt class="docutils literal">list</tt> argument is used to view a list of roles that are currently available on the Chef server.

Syntax¶

This argument has the following syntax:

$ knife role list

Options¶

This argument has the following options:

<tt class="docutils literal">-w</tt>, <tt class="docutils literal">--with-uri</tt>

Use to show the corresponding URIs.

Examples¶

The following examples show how to use this Knife subcommand:

View a list of roles

To view a list of roles on the Chef server and display the URI for each role returned, enter:

$ knife role list -w

show¶

The <tt class="docutils literal">show</tt> argument is used to view the details of a role.

Syntax¶

This argument has the following syntax:

$ knife role show ROLE_NAME

Options¶

This argument has the following options:

<tt class="docutils literal">-a ATTR</tt>, <tt class="docutils literal">--attribute ATTR</tt>

The attribute (or attributes) to show.

Examples¶

The following examples show how to use this Knife subcommand:

Show as JSON data

To view information in JSON format, use the <tt class="docutils literal">-F</tt> common option as part of the command like this:

$ knife role show devops -F json

Other formats available include <tt class="docutils literal">text</tt>, <tt class="docutils literal">yaml</tt>, and <tt class="docutils literal">pp</tt>.

Show as raw JSON data

To view node information in raw JSON, use the <tt class="docutils literal">-l</tt> or <tt class="docutils literal">--long</tt> option:

knife node show -l -F json <node_name>

and/or:

knife node show -l --format=json <node_name>


text:
package java.nio.channels;

public class NoConnectionPendingException
  extends java.lang.IllegalStateException{
  // Constructors

  public NoConnectionPendingException(){
    super();
  }
}


text:
Edit information about feedback provider.

<form method="POST" class="post-form">{% csrf_token %}
	{{ form.as_p }}
	<button type="submit" class="save btn btn-default">Save</button>
</form>

	Go to Degree360:requestFeedback?


text:
// This file implements logic for lowering TensorFlow dialect's control flow to
// the XLA dialect.

#include <cstddef>
#include <cstdint>
#include <iterator>
#include <numeric>
#include <tuple>

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
#include "mlir/IR/Operation.h"  // from @llvm-project
#include "mlir/IR/OperationSupport.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassRegistry.h"  // from @llvm-project
#include "mlir/Transforms/RegionUtils.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops.h"

using mlir::PassRegistration;

namespace mlir {
namespace mhlo {
namespace {

#define GEN_PASS_DEF_LEGALIZETFCONTROLFLOW
#include "tensorflow/compiler/mlir/xla/transforms/xla_legalize_tf_passes.h.inc"

class LegalizeTFControlFlow
    : public impl::LegalizeTFControlFlowBase<LegalizeTFControlFlow> {
 public:
  void runOnOperation() override;
};
}  // namespace

std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
createLegalizeTFControlFlowPass() {
  return std::make_unique<LegalizeTFControlFlow>();
}

namespace {

void Detuple(Value tuple, ValueRange replace, OpBuilder* builder) {
  // De-tuple the results of the xla hlo if result.
  for (auto result_it : llvm::enumerate(replace)) {
    auto get_tuple_value = builder->create<mhlo::GetTupleElementOp>(
        result_it.value().getLoc(), tuple, result_it.index());
    result_it.value().replaceAllUsesWith(get_tuple_value);
  }
}

// For mlir::IfOp or mlir::CaseOp, replace the uses of their region's block
// arguments with 'implicit_operands'. Here | 'implicit_operands' | == Number of
// arguments in any of the regions in IfOp or CaseOp.
void ReplaceBlockArgumentsWithImplicitOperands(
    mlir::Operation* op, llvm::ArrayRef<mlir::Value> implicit_operands) {
  assert((mlir::dyn_cast<mlir::mhlo::IfOp>(*op) ||
          mlir::dyn_cast<mlir::mhlo::CaseOp>(*op)) &&
         "Unexpected mlir op in ReplaceBlockArgumentsWithImplicitOperands!");

  for (auto& region : op->getRegions()) {
    int implicit_operand_index = 0;
    for (auto arg : region.getArguments()) {
      assert(implicit_operand_index < implicit_operands.size());
      arg.replaceAllUsesWith(implicit_operands[implicit_operand_index++]);
    }

    region.front().eraseArguments(0, region.getNumArguments());
  }
}

// Imports the source region into the destination region. MHLO supports
// multiple arguments per branch and multiple returns which are individually
// tupled together during export to XLA. This tupling is needed as XLA if/while
// operation only supports one argument per branch and a single return value.
// `tuple_arg` allows any branch that requires additional arguments to have
// their values be tupled together. Similarly, `tuple_return` allows the results
// of the if/while operation to be tupled together.
void ImportXlaRegion(mlir::func::FuncOp func, Region* dest_region, Location loc,
                     bool tuple_return = true, bool tuple_arg = true) {
  OpBuilder builder(dest_region);

  auto entry_block = builder.createBlock(dest_region);
  func::CallOp result;
  if (!tuple_arg) {
    auto inputs = func.getFunctionType().getInputs();
    auto args = entry_block->addArguments(
        inputs, SmallVector<Location>(inputs.size(), loc));
    ArrayRef<Value> callop_args(args.begin(), args.end());
    result = builder.create<func::CallOp>(loc, func, callop_args);
  } else {
    auto tuple_arg = entry_block->addArgument(
        builder.getTupleType(func.getFunctionType().getInputs()), loc);
    llvm::SmallVector<Value, 4> detupled_args;
    detupled_args.reserve(func.getNumArguments());

    for (int64_t i = 0, s = func.getNumArguments(); i < s; i++) {
      auto extract = builder.create<GetTupleElementOp>(loc, tuple_arg, i);
      detupled_args.push_back(extract);
    }

    result = builder.create<func::CallOp>(loc, func, detupled_args);
  }

  if (!tuple_return) {
    builder.create<mhlo::ReturnOp>(loc, result.getResults());
  } else {
    auto tuple_op = builder.create<TupleOp>(loc, result.getResults());
    builder.create<mhlo::ReturnOp>(loc, tuple_op.getResult());
  }
}

void LowerIf(TF::IfOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  SmallVector<Value, 3> inputs(op.getInput());

  // Create the new `mhlo.if` op.
  auto if_op =
      builder.create<mhlo::IfOp>(loc, op.getResultTypes(), op.getCond());

  // Import the regions for both the true and false cases. These regions
  // must be updated to tuple the return results together and use the xla hlo
  // return op.
  ImportXlaRegion(op.then_function(), &if_op.getTrueBranch(), loc,
                  /*tuple_return=*/false, /*tuple_arg=*/false);
  ImportXlaRegion(op.else_function(), &if_op.getFalseBranch(), loc,
                  /*tuple_return=*/false, /*tuple_arg=*/false);

  // Replace the uses of block-arguments of the IfOp with the
  // implicit_operands.
  ReplaceBlockArgumentsWithImplicitOperands(if_op.getOperation(), inputs);

  op->replaceAllUsesWith(if_op);
  op.erase();
}

void LowerCase(TF::CaseOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  SmallVector<Value, 4> inputs(op.getInput());

  // Create the new `mhlo.case` op.
  auto case_op = builder.create<mhlo::CaseOp>(
      loc, op.getResultTypes(), op.getBranchIndex(), op.getBranches().size());

  // Import the regions for all branches.
  for (unsigned i = 0; i < op.num_branches(); ++i) {
    mlir::func::FuncOp branch_func = op.branch_function(i);
    ImportXlaRegion(branch_func, &case_op.getBranches()[i], loc,
                    /*tuple_return=*/false, /*tuple_arg=*/false);
  }

  // Replace the uses of block-arguments of the IfOp with the
  // implicit_operands.
  ReplaceBlockArgumentsWithImplicitOperands(case_op.getOperation(), inputs);

  op.replaceAllUsesWith(case_op);
  op.erase();
}

void LowerWhile(TF::WhileOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  // XLA prefers tuple arguments for control flow due to XLA not supporting
  // multiple return values.
  SmallVector<Value, 3> inputs(op.getInput());
  builder.setInsertionPoint(op);

  // Create the new `mhlo.while` op with inputs.
  auto while_op =
      builder.create<mhlo::WhileOp>(loc, op.getResultTypes(), inputs);

  // Import the regions for both the cond and body.
  ImportXlaRegion(op.body_function(), &while_op.getBody(), loc,
                  /*tuple_return=*/false, /*tuple_arg=*/false);
  ImportXlaRegion(op.cond_function(), &while_op.getCond(), loc,
                  /*tuple_return=*/false, /*tuple_arg=*/false);

  op->replaceAllUsesWith(while_op);
  op.erase();
}

// Replaces all block arguments of a block with a single block arg of Tuple
// type `tuple_type`. Single block arguments are removed and remapped to
// get_tuple_element(tuple_arg, index).
void ReplaceBlockArgs(Block* block, Type tuple_type, OpBuilder* builder) {
  auto tuple_arg = block->addArgument(tuple_type, block->getParent()->getLoc());
  Detuple(tuple_arg, block->getArguments().drop_back(1), builder);
  for (int i = block->getNumArguments() - 2; i >= 0; --i)
    block->eraseArgument(i);
}

// Replaces implicitly captured value uses with block arguments.
llvm::SmallVector<Value, 4> ReplaceImplicitInputs(
    Block* block, int offset, ArrayRef<Value> implicit_inputs) {
  llvm::SmallVector<Value, 4> implicit_input_elements;
  implicit_input_elements.reserve(implicit_inputs.size());

  Region* region = block->getParent();

  for (auto& implicit_input : llvm::enumerate(implicit_inputs)) {
    Value implicit_input_value = implicit_input.value();
    BlockArgument arg = block->getArgument(implicit_input.index() + offset);
    implicit_input_elements.emplace_back(arg);
    for (auto& use :
         llvm::make_early_inc_range(implicit_input_value.getUses())) {
      if (!region->isAncestor(use.getOwner()->getParentRegion())) continue;
      use.set(arg);
    }
  }

  return implicit_input_elements;
}

// Replaces implicitly captured value uses with tuple block argument.
// get_tuple_element's are created to extract specific values. Values from
// get_tuple_element's are returned in the order of `implicit_inputs`.
llvm::SmallVector<Value, 4> ReplaceImplicitInputsWithTupleElements(
    Block* block, int offset, ArrayRef<Value> implicit_inputs,
    OpBuilder* builder) {
  llvm::SmallVector<Value, 4> implicit_input_elements;
  implicit_input_elements.reserve(implicit_inputs.size());

  Region* region = block->getParent();
  assert(block->getNumArguments() == 1);

  BlockArgument tuple_arg = block->getArgument(0);
  for (auto& implicit_input : llvm::enumerate(implicit_inputs)) {
    Value implicit_input_value = implicit_input.value();
    auto get_tuple_element = builder->create<mhlo::GetTupleElementOp>(
        implicit_input_value.getLoc(), tuple_arg,
        implicit_input.index() + offset);
    implicit_input_elements.emplace_back(get_tuple_element.getResult());
    for (auto& use :
         llvm::make_early_inc_range(implicit_input_value.getUses())) {
      if (!region->isAncestor(use.getOwner()->getParentRegion())) continue;
      use.set(get_tuple_element.getResult());
    }
  }

  return implicit_input_elements;
}

// Finds and replaces implicitly captured value uses with tuple block argument.
// A tuple of implicitly captured values is also created and returned, for use
// as an operand to the associated mhlo control flow op.
Value TupleImplicitInputs(Region& region, Location loc, OpBuilder* builder) {
  llvm::SetVector<Value> implicit_inputs;
  getUsedValuesDefinedAbove(region, region, implicit_inputs);
  llvm::ArrayRef<Value> implicit_inputs_ref = implicit_inputs.getArrayRef();
  Value tuple_input = builder->create<mhlo::TupleOp>(loc, implicit_inputs_ref);
  Block& block = region.front();
  // `tf.CaseRegion`/`tf.IfRegion` are expected to have no block arguments and
  // instead all inputs used by their branch regions are implicitly captured
  // from above.
  assert(block.getNumArguments() == 0);
  block.addArgument(tuple_input.getType(), loc);
  builder->setInsertionPointToStart(&block);
  ReplaceImplicitInputsWithTupleElements(&block, /*offset=*/0,
                                         implicit_inputs_ref, builder);
  return tuple_input;
}

// Replaces block terminator (tf.Yield) with `mhlo.return`. Additional results
// can be returned if `extra_results` is not empty. If `tuple_return` is
// set, a tuple of the return values will be set as the terminator operand.
void ReplaceTerminator(Block* block, ArrayRef<Value> extra_results,
                       OpBuilder* builder, bool tuple_return = true) {
  Operation* terminator = block->getTerminator();
  assert(isa<TF::YieldOp>(terminator));
  Location loc = terminator->getLoc();

  builder->setInsertionPoint(terminator);
  auto results = llvm::to_vector<4>(terminator->getOperands());
  results.append(extra_results.begin(), extra_results.end());
  if (tuple_return) {
    auto tuple_results = builder->create<mhlo::TupleOp>(loc, results);
    builder->create<mhlo::ReturnOp>(loc, tuple_results.getResult());
  } else {
    builder->create<mhlo::ReturnOp>(loc, results);
  }

  terminator->erase();
}

void LowerIfRegion(TF::IfRegionOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  builder.setInsertionPoint(op);
  ReplaceTerminator(&op.getThenBranch().front(), /*extra_results=*/{}, &builder,
                    /*tuple_return=*/false);

  builder.setInsertionPoint(op);
  ReplaceTerminator(&op.getElseBranch().front(), /*extra_results=*/{}, &builder,
                    /*tuple_return=*/false);

  // Create the new `mhlo.if` op and take ownership of regions from
  // `tf.IfRegion` op.
  builder.setInsertionPoint(op);
  auto if_op =
      builder.create<mhlo::IfOp>(loc, op.getResultTypes(), op.getCond());
  if_op.getTrueBranch().takeBody(op.getThenBranch());
  if_op.getFalseBranch().takeBody(op.getElseBranch());

  // Replace all uses of `op` results with that of `mhlo.IfOp`.
  op->replaceAllUsesWith(if_op);

  op.erase();
}

void LowerCaseRegion(TF::CaseRegionOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  for (Region& region : op.getBranches()) {
    builder.setInsertionPoint(op);
    ReplaceTerminator(&region.front(), /*extra_results=*/{}, &builder,
                      /*tuple_return=*/false);
  }

  // Create the new `mhlo.case` op and take ownership of regions from
  // `tf.CaseRegion` op.
  builder.setInsertionPoint(op);
  auto case_op = builder.create<mhlo::CaseOp>(
      loc, op.getResultTypes(), op.getBranchIndex(), op.getBranches().size());
  for (auto region : llvm::zip(case_op.getBranches(), op.getBranches()))
    std::get<0>(region).takeBody(std::get<1>(region));

  // Replace all uses of `op` results with that of `mhlo.CaseOp`.
  op.replaceAllUsesWith(case_op);
  op.erase();
}

void LowerWhileRegion(TF::WhileRegionOp op) {
  Location loc = op.getLoc();
  OpBuilder builder(op);

  SmallVector<Value, 3> inputs(op.getInput());
  const int inputs_size = inputs.size();
  llvm::SetVector<Value> implicit_inputs;
  getUsedValuesDefinedAbove(op.getOperation()->getRegions(), implicit_inputs);
  inputs.append(implicit_inputs.begin(), implicit_inputs.end());

  builder.setInsertionPoint(op);

  // Create the new `mhlo.while` op with 'inputs'. Implicit inputs are also
  // returned.
  auto while_result_types = llvm::to_vector<4>(op.getResultTypes());
  while_result_types.reserve(while_result_types.size() +
                             implicit_inputs.size());
  for (const auto& implicit_input : implicit_inputs)
    while_result_types.emplace_back(implicit_input.getType());
  auto while_op =
      builder.create<mhlo::WhileOp>(loc, while_result_types, inputs);

  // Rewrite cond and associated block arguments and terminator. Ownership of
  // cond region is transfered over from `tf.WhileRegion` to `mhlo.while`.
  Region& cond = while_op.getCond();
  cond.takeBody(op.getCond());
  Block& cond_block = cond.front();
  builder.setInsertionPointToStart(&cond_block);

  // Add args corresponding to 'implicit_inputs'.
  for (const auto& implicit_input : implicit_inputs)
    cond_block.addArgument(implicit_input.getType(), loc);
  ReplaceImplicitInputs(&cond_block, inputs_size,
                        implicit_inputs.getArrayRef());
  // Cond always returns a single result of bool type.
  ReplaceTerminator(&cond_block, /*extra_results=*/{}, &builder,
                    /*tuple_return=*/false);

  // Rewrite body and associated block arguments and terminator. Ownership of
  // body region is transfered over from `tf.WhileRegion` to `mhlo.while`.
  Region& body = while_op.getBody();
  body.takeBody(op.getBody());
  Block& body_block = body.front();
  builder.setInsertionPointToStart(&body_block);
  // Add args corresponding to 'implicit_inputs'.
  for (const auto& implicit_input : implicit_inputs)
    body_block.addArgument(implicit_input.getType(), loc);
  auto implicit_input_elements = ReplaceImplicitInputs(
      &body_block, inputs_size, implicit_inputs.getArrayRef());
  ReplaceTerminator(&body_block, implicit_input_elements, &builder, false);

  // Replace all uses of `op` results with that of `mhlo.while`.
  builder.setInsertionPoint(op);
  if (while_op.getNumResults() > 1) {
    for (const auto& result_it : llvm::enumerate(op.getResults()))
      result_it.value().replaceAllUsesWith(
          while_op.getResult(result_it.index()));
  } else {
    op->replaceAllUsesWith(while_op);
  }
  op.erase();
}
}  // namespace

void LegalizeTFControlFlow::runOnOperation() {
  getOperation().walk([&](Operation* op) {
    if (auto while_op = dyn_cast<TF::WhileOp>(op)) {
      LowerWhile(while_op);
      return;
    }
    if (auto while_region_op = dyn_cast<TF::WhileRegionOp>(op)) {
      LowerWhileRegion(while_region_op);
      return;
    }
    if (auto if_op = dyn_cast<TF::IfOp>(op)) {
      LowerIf(if_op);
      return;
    }
    if (auto if_region_op = dyn_cast<TF::IfRegionOp>(op)) {
      LowerIfRegion(if_region_op);
      return;
    }
    if (auto case_op = dyn_cast<TF::CaseOp>(op)) {
      LowerCase(case_op);
      return;
    }
    if (auto case_region_op = dyn_cast<TF::CaseRegionOp>(op)) {
      LowerCaseRegion(case_region_op);
      return;
    }
  });
}
}  // namespace mhlo
}  // namespace mlir


text:
'''
Contains generic methods and information (musical keys, MIDI instrument names) to be used by all
MusicAgents in generation of their music.
'''
import pyknon, operator, numpy, random, nltk, math, re
from os import listdir
from os.path import isfile, join
from pyknon.music import NoteSeq, Rest

class MusicHelper:
    '''
    A class that contains useful methods for creating music from text, analyzing the music, and modifying it.
    '''
    #Hard-coded list of musical keys and their relative keys
    relative_keys = {
    'cmajor':'aminor',\
    'gmajor':'eminor',\
    'dmajor':'bminor',\
    'amajor':'fsharpminor',\
    'emajor':'csharpminor',\
    'bmajor':'gsharpminor',\
    'fsharpmajor':'dsharpminor',\
    'dflatmajor':'bflatminor',\
    'aflatmajor':'fminor',\
    'eflatmajor':'cminor',\
    'bflatmajor':'gminor',\
    'fmajor':'dminor',\
    'aminor':'cmajor',\
    'eminor':'gmajor',\
    'bminor':'dmajor',\
    'fsharpminor':'amajor',\
    'csharpminor':'emajor',\
    'gsharpminor':'bmajor',\
    'dsharpminor':'fsharpmajor',\
    'bflatminor':'dflatmajor',\
    'fminor':'aflatmajor',\
    'cminor':'eflatmajor',\
    'gminor':'bflatmajor',\
    'dminor':'fmajor'
    }

    def __init__(self):
        self.music_keys = {}
        self._read_keys()

    def _read_keys(self, mypath="keys/"):
        '''
        Initialization method that reads in all available keys, in a specified path.

        :param str mypath: The location of the keys to be read
        '''
        key_files = [f  for f in listdir(mypath) if isfile(join(mypath, f))]
        for key in key_files:
            new_key = key.replace(".txt", "")
            key_notes = NoteSeq("file://" + mypath + key)
            self.music_keys[new_key] = key_notes

    def determine_dominant_key(self, notes):
        '''
        Takes a list of notes and compares it to each key, then returns the key which the
        notes match best.

        :param str notes: A list of notes in string format or as a pyknon.music.NoteSeq.
        :returns: A string representation of the dominant key (i.e. 'fminor')
        '''
        if isinstance(notes, pyknon.music.NoteSeq):
            test_seq = notes
        else:
            if isinstance(notes, str):
                test_seq = NoteSeq(notes)
            elif isinstance(notes, list):
                test_seq = NoteSeq(''.join(notes))
            else:
                raise ValueError('Notes supplied to determine_dominant_key not in a known format (list, string, NoteSeq)')

        key_score = {}
        for key in self.music_keys.keys():
            key_score[key] = 0
        for note in test_seq:
            for key, value in self.music_keys.items():
                if note in value:
                    key_score[key] = key_score[key] + 1

        dominant_key = max(key_score, key=key_score.get)

        return dominant_key

    @staticmethod
    def convert_phrase_to_notes(phrase):
        '''
        Takes a text phrase and converts it to musical notes by extracting characters that represent
        musical notes.

        :param str phrase: Any string of text, to be converted to musical notes
        :returns: A list of notes extracted from the string.
        '''
        notes = []

        for word in phrase:
            for char in word:
                c = char.lower()
                if c == 'c':
                    notes.append("C")
                elif c == 'd':
                    notes.append("D")
                elif c == 'e':
                    notes.append("E")
                elif c == 'f':
                    notes.append("F")
                elif c == 'g':
                    notes.append("G")
                elif c == 'a':
                    notes.append("A")
                elif c == 'b':
                    notes.append("B")

        return notes

    def conform_notes_to_key(self, notes, music_key):
        '''
        Takes a list of notes, and a music key and ensures that every note either
        belongs to that key or to its relative key.

        :param str notes: The notes to be matched
        :param str music_key: The name of the key to be matched (i.e. 'cmajor')
        :returns: A list of notes that are all in the specified key or its relative key.
        '''
        if isinstance(notes, NoteSeq):
            test_notes = notes
        else:
            test_notes = NoteSeq(' '.join(notes))

        new_note_list = []

        key_notes = self.music_keys[music_key]
        relative_key = self.relative_keys[music_key]

        if relative_key:
            relative_key_notes = self.music_keys[relative_key]

        for note in test_notes:
            if note in key_notes or note in relative_key_notes:
                new_note_list.append(note)

            else:
                new_note = numpy.random.choice(key_notes + relative_key_notes)
                new_note_list.append(new_note)

        return new_note_list

    def convert_tracks_to_string(self, tracks):
        '''
        Changes a list of tracks or notes to a string for easy comparison to other
        track/note lists.  Used primarily to compute levenshtein distance between tracks.

        :param list method: A list of tracks or notes
        :returns: A string of the notes
        '''
        note_str = str(tracks)
        #remove all not-note elements of the track_list in order to evaluate only the notes sequence
        note_str = re.sub('[<>:R.#, ]', '', note_str)
        note_str = ''.join([i for i in note_str if not i.isdigit()])
        note_str = note_str.replace("Seq", "")
        note_str = note_str.replace("[", "")
        note_str = note_str.replace("]", "")
        return note_str

    def derive_tracks_from_lyrics(self, lyrics, notes, track_duration, method):
        '''
        Attempts to find patterns in lyrics to be paired with the given notes
        to create new tracks of a specified duration

        :param str lyrics:The lyrics from which to derive music
        :param NoteSequ notes: The notes to be utilized in track creation
        :param int track_duration: The optimal length of the tracks, in seconds
        :param list method:A list of invention methods that derive data from text
        :returns: A list of NoteSeqs that represents musical tracks
        '''
        num_notes = len(notes)
        lyrics_sentences = lyrics.replace("?", ".").replace("!", ".").split(".")
        #Remove tiny sentences, if any
        lyrics_sentences = [s for s in lyrics_sentences if len(s) > 5]
        num_sentences = len(lyrics_sentences)

        track_list = list()
        #Skip first sentence, as the Lead track will be based on it already
        #otherwise create a track for each sentence
        for i in range(1, min(3,num_sentences)):
            #Count the words in this sentence
            lyric_sentence = lyrics_sentences[i]
            lyric_words = nltk.word_tokenize(lyric_sentence)
            num_words = len(lyric_words)
            #Count the number of characters in each word
            list_of_char_counts = list()
            for j in range(0,len(lyric_words)):
                list_of_char_counts.append(len(lyric_words[j]))
            num_chars_total = sum([cnt for cnt in list_of_char_counts])

            #Every other track picks a pattern length differently
            #but all tracks use the agent's invention methods
            if i % 2 == 0:
                pattern_length = max(3,method[0](lyric_sentence) % 8)
                pattern_accent = method[1](lyric_sentence) % 3
                accent_occur = max(1,method[2](lyric_sentence) % 12)
                inversion_accent = method[3](lyric_sentence) % 6
                inversion_occur = max(1,method[4](lyric_sentence) % 10)
                #Aim to start shortly before the lead track
                target_duration = track_duration * 1.05
                note_vol = 85
            else:
                pattern_length = max(3,method[4](lyric_sentence) % 12)
                pattern_accent = method[3](lyric_sentence) % 3
                accent_occur = max(1,method[2](lyric_sentence) % 16)
                inversion_accent = method[1](lyric_sentence) % 5
                inversion_occur = max(1,method[0](lyric_sentence) % 8)
                #Aim for a lead-in before the other tracks
                target_duration = track_duration * 1.1
                note_vol = 80

            #Give notes equal time, in accordance with represented word length, plus time for rests
            duration_unit = (target_duration / (num_words  * pattern_length * num_chars_total)) - num_words

            #Repeat the pattern equal to the number of words in the sentence
            this_track = NoteSeq()
            for n in range(0, num_words):
                for m in range(0, pattern_length):
                    note_to_append = m % num_notes
                    note = notes[note_to_append]
                    note.volume = note_vol

                    #Invert the pattern this time, if the invention method calls for it
                    if n % inversion_occur == 2:
                        note = note.inversion(inversion_accent)

                    duration_count = max(1,m % list_of_char_counts[n])
                    note.duration = duration_count * duration_unit
                    #Transpose this note, if the invention method calls for it
                    if m % accent_occur == 3:
                        if m // accent_occur % 2 == 0:
                            note = note.transposition(pattern_accent)
                        else:
                            note = note.transposition(-pattern_accent)
                    this_track.append(note)
                #Rest for a second between tracks
                this_track.append(Rest(1))

            #Add the completed track
            track_list.append(this_track)

        return track_list

    @staticmethod
    def determine_theme(word):
        '''
        This method takes a word supplied by the agent and attempts to match items
        as a substring of themes encompassed by word lists.  If a matching theme
        is found then a list of MIDI instrument numbers is returned.
        *A substring will match (word=old, will_match=olden)*

        :param str word: The word to use as a potential theme match
        :returns: A tuple containing tempo and a list of MIDI instruments in int format.
        '''
        #Filter out meaningless words
        if word in "and from say her him his she had the their for one your all out ass are how has very each own off "\
                    "fit":
            return None
        if word in "children kids young baby youth age kid bosom asleep nap quiet silence discovery learn education "\
                    "find taught teacher lesson boy girl imagination imagine":
            return (160,[75, 10, 15]) #76-Pan Flute, 11-Music Box, 16-Dulcimer

        if word in "sky nature tree forest earth atmosphere air bird "\
                    "tweet nest egg flight breasted morning sunrise day explore happy happiness calmly freshest "\
                    "sail boat ocean sea pelican seagulls wings Captain sailors ship starboard port dock feathers "\
                    "seaworthy":
            return (180, [99, 122, 123]) #100-Atmosphere, 123-Seashore, 124-Bird Tweet

        if word in "olden yearning ancients timely slowing pine wishing wistful lonely harkening past year long ago "\
                    "true truly travel men return":
            return (140, [109, 89, 117]) #110-Bagpipe, 90-Warm synth, 118-Melodic Drum

        if word in "evil danger primal attacked attacking offense enemy dungeon wounded bleed blood murder "\
                    "death kill festering mortal peril endangered threatened ":
            return (600,[30, 85, 114]) #31-Distortion Guitar, 86-Voice, 115-Steel drums

        if word in "voices angels choir holy blessing prayer blessed fortunate fortune lucky benefit boon "\
                    "lucked chance godly heavenly golden happily peace above gods divine Christmas":
            return (180,[48, 52, 98]) #49-String Ensemble, 53-Choir Ahs, 99-Crystal

        if word in "guitar solo rocked rocking tune played song strummed picked heard bass electric music ":
            return (240, [25, 32, 117]) #26-Steel guitar,  33-Acoustic bass, 118-Melodic Tom

        if word in "native indigenous locally primitive folklore community social friendly smallest society "\
                    "farming garden landscape enjoyment enjoyed relaxed relaxation relaxing peaceful satisfied":
            return (160, [78, 12, 116]) #79-Whistle, 13-Marimba, 117-Taiko Drum

        if word in "clock minutes hours seconds chronological timely":
            return (160, [14, 13, 116]) #15-Tubular Bells, 14-xylophone, 117-Taiko drum

        if word in "strings wind breeze orchestra elegant elegance somber precision ritz class impressive":
            return (120, [40, 42, 46]) #40-Violin, 43-Cello, 47-Harp

        if word in "moon mystical nighttime dusk evening stars stargazing space planets sense traveler alien atmosheric"\
                    "strata radiation phenomenon shone sparkle shining distant":
            return (160, [85, 88, 13]) #86-Voice, , 89-New Age, 14-Xylophone

        if word in "rusty broken cracked failing abused large fallen abandon dismayed":
            return (180, [22, 70, 58]) #23-Harmonica, 71-Bassoon, 59-Tuba

        if word in "adventure encounter showdown lingering nearby thousand circles battle lurking sinister":
            return (200, [44, 18, 119]) #45-Tremolo Strings, 19-Rock Organ, 120-Reverse Cymbal

        if word in "aqueduct river stream flowing filled filling splashing swimming liquid dripping water flooded "\
                    "spilling drenched soaking soaked moistened slick puddles puddling drenching weather rain wind cloud "\
                    "drizzle mist ":
            return (140, [40, 96, 123]) #41-Violin, 97-Rain, 123-Seashore

        if word in "cheerful happy pleasant jolly happiness joyful carefree":
            return (120, [79, 75, 76]) #80-Ocarina, 76-Pan flute, 77-Blown bottle

        if word in "alien terrifying terror frightening ghastly abomination creature predator beastly foul scared"\
                    "foreign infernal snuff":
            return (600, [101, 103, 127]) #102-Goblins, 104-Scifi, 128-Gunshots

        if word in "mountains rocks entombed cliffside canyons boulders plateau deserted cactus underneath":
            return (240, [71, 81, 114])#72 - Clarinet, 82-Sawtooth, 115-Steel Drums

        if word in "fatigue tired weary exhausted depleted expired extinct":
            return (140, [58, 80, 113])#59 Brass-Tuba, 81-Square, 114-Agogo

        if word in "random lunatics crazy gibberish crazed bizarre bewildering nonsense unknowable":
            random_tempo = random.randint(120,250)
            random_instr1 = random.randint(1, 114) #Random lead instrument
            random_instr2 = random.randint(1, 127) #Random anything
            random_instr3 = random.randint(113, 121) #Random percussion
            return (random_tempo, [random_instr1, random_instr2, random_instr3])

    @staticmethod
    def determine_instrument(midi_int):
        '''
        Static method that identifies a category and instrument for a given int representing a MIDI instrument.

        :param int midi_int: The int of the MIDI instrument
        :returns: A tuple containing the category and instrument name for the given int.
        '''
        #Add one because our MIDI writer uses 0-based index
        midi_int = midi_int + 1

        #Set the default
        category = 'None'
        instrument = 'None'

        if  midi_int < 1 or midi_int > 128:
            return type_instrument

        if midi_int <= 8:
            category = 'Piano'
            instrument = {
                1 : 'Acoustic Grand Piano',
                2 : 'Bright Acoustic Piano',
                3 : 'Electric Grand Piano',
                4 : 'Honky-tonk Piano',
                5 : 'Electric Piano 1',
                6 : 'Electric Piano 2',
                7 : 'Harpsichord',
                8 : 'Clavinet'
            }[midi_int]
        elif midi_int <= 16:
            category = 'Chromatic Percussion'
            instrument = {
                9  : 'Celesta',
                10 : 'Glockenspiel',
                11 : 'Music Box',
                12 : 'Vibraphone',
                13 : 'Marimba',
                14 : 'Xylophone',
                15 : 'Tubular Bells',
                16 : 'Dulcimer'
            }[midi_int]

        elif midi_int <= 24:
            category = 'Organ'
            instrument = {
                17 : 'Drawbar Organ',
                18 : 'Percussive Organ',
                19 : 'Rock Organ',
                20 : 'Church Organ',
                21 : 'Reed Organ',
                22 : 'Accordion',
                23 : 'Harmonica',
                24 : 'Tango Accordion'
            }[midi_int]

        elif midi_int <= 32:
            category = 'Guitar'
            instrument = {
                25 : 'Acoustic Guitar (nylon)',
                26 : 'Acoustic Guitar (steel)',
                27 : 'Electric Guitar (jazz)',
                28 : 'Electric Guitar (clean)',
                29 : 'Electric Guitar (muted)',
                30 : 'Overdriven Guitar',
                31 : 'Distortion Guitar',
                32 : 'Guitar harmonics'
            }[midi_int]

        elif midi_int <= 40:
            category = 'Bass'
            instrument = {
                33 : 'Acoustic Bass',
                34 : 'Electric Bass (finger)',
                35 : 'Electric Bass (pick)',
                36 : 'Fretless Bass',
                37 : 'Slap Bass 1',
                38 : 'Slap Bass 2',
                39 : 'Synth Bass 1',
                40 : 'Synth Bass 2'
            }[midi_int]

        elif midi_int <= 52:
            category = 'Strings'
            instrument = {
                41 : 'Violin',
                42 : 'Viola',
                43 : 'Cello',
                44 : 'Contrabass',
                45 : 'Tremolo Strings',
                46 : 'Pizzicato Strings',
                47 : 'Orchestral Harp',
                48 : 'Timpani',
                49 : 'String Ensemble 1',
                50 : 'String Ensemble 2',
                51 : 'Synth Strings 1',
                52 : 'Synth Strings 2'
            }[midi_int]

        elif midi_int <= 56:
            category = 'Voice'
            instrument = {
                53 : 'Choir Aahs',
                54 : 'Voice Oohs',
                55 : 'Synth Voice',
                56 : 'Orchestra Hit'
            }[midi_int]

        elif midi_int <= 64:
            category = 'Brass'
            instrument = {
                57 : 'Trumpet',
                58 : 'Trombone',
                59 : 'Tuba',
                60 : 'Muted Trumpet',
                61 : 'French Horn',
                62 : 'Brass Section',
                63 : 'Synth Brass 1',
                64 : 'Synth Brass 2'
            }[midi_int]

        elif midi_int <= 72:
            category = 'Reed'
            instrument = {
                65 : 'Soprano Sax',
                66 : 'Alto Sax',
                67 : 'Tenor Sax',
                68 : 'Baritone Sax',
                69 : 'Oboe',
                70 : 'English Horn',
                71 : 'Bassoon',
                72 : 'Clarinet'
            }[midi_int]

        elif midi_int <= 80:
            category = 'Pipe'
            instrument = {
                73 : 'Piccolo',
                74 : 'Flute',
                75 : 'Recorder',
                76 : 'Pan Flute',
                77 : 'Blown Bottle',
                78 : 'Shakuhachi',
                79 : 'Whistle',
                80 : 'Ocarina'
            }[midi_int]

        elif midi_int <= 88:
            category = 'Synth Lead'
            instrument = {
                81 : 'Square',
                82 : 'Sawtooth',
                83 : 'Calliope',
                84 : 'Chiff',
                85 : 'Charang',
                86 : 'Voice',
                87 : 'Fifths',
                88 : '(Bass + Lead)'
            }[midi_int]

        elif midi_int <= 96:
            category = 'Synth Pad'
            instrument = {
                89 : 'New age',
                90 : 'Warm',
                91 : 'Polysynth',
                92 : 'Choir',
                93 : 'Bowed',
                94 : 'Metallic',
                95 : 'Halo',
                96 : 'Sweep'
            }[midi_int]

        elif midi_int <= 104:
            category = 'Synth Effects'
            instrument = {
                97 : 'Rain',
                98 : 'Soundtrack',
                99 : 'Crystal',
                100 : 'Atmosphere',
                101 : 'Brightness',
                102 : 'Goblins',
                103 : 'Echoes',
                104 : 'Sci-fi'
            }[midi_int]

        elif midi_int <= 112:
            category = 'Ethnic'
            instrument = {
                105 : 'Sitar',
                106 : 'Banjo',
                107 : 'Shamisen',
                108 : 'Koto',
                109 : 'Kalimba',
                110 : 'Bag pipe',
                111 : 'Fiddle',
                112 : 'Shanai'
            }[midi_int]

        elif midi_int <= 119:
            category = 'Percussive'
            instrument = {
                113 : 'Tinkle Bell',
                114 : 'Agogo',
                115 : 'Steel Drums',
                116 : 'Woodblock',
                117 : 'Taiko Drum',
                118 : 'Melodic Tom',
                119 : 'Synth Drum'
            }[midi_int]

        else:
            category = 'Sound Effect'
            instrument = {
                120 : 'Reverse Cymbal',
                121 : 'Guitar Fret Noise',
                122 : 'Breath Noise',
                123 : 'Seashore',
                124 : 'Bird Tweet',
                125 : 'Telephone Ring',
                126 : 'Helicopter',
                127 : 'Applause',
                128 : 'Gunshot'
            }[midi_int]

        return (category, instrument)


text:
using System;

namespace Telerik.Data.Core.Fields
{
    /// <summary>
    /// Represents an abstraction of a property info.
    /// </summary>
    internal interface IDataFieldInfo
    {
        /// <summary>
        /// Gets name of the property.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Gets the data type of the property.
        /// </summary>
        /// <value>
        /// The <see cref="Type"/> of the data.
        /// </value>
        Type DataType { get; }

        /// <summary>
        /// Gets the expected role of this property.
        /// </summary>
        FieldRole Role { get; }

        /// <summary>
        /// Gets the display-friendly name of the property.
        /// </summary>
        string DisplayName { get; }

        bool Equals(IDataFieldInfo info);
    }
}


text:
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

    </button>
    Home

            Perfil

            Anuncie

            Contato


text:
		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/beige.css">

Image segmentation with PDEs

🗲matt hancock🗲

Image analysis

Detection: where is the thing?

Recognition: what is the thing?

Segmentation: where's the borders of the thing?

Segmentation with PDEs

Tell curve/surface how to move → PDE

Minimize energy functional → PDE

Numerically solve PDE → iterative segmentation method

Example 1

                            Curve velocity
                            is in
                            the outward direction
                            with
                            speed decaying with image edge strength

                            xt
                            =
                            R xs / ||xs||
                            ×

                            f(||D(Gσ∗I)(x)||)

                    <input class="animation-frames-controls" example="1"
                     type="range" value=0 min=0 max=200 step=10>

Example 1 (initialization failure)

                            Curve velocity
                            is in
                            the outward direction
                            with
                            speed decaying with image edge strength

                            xt
                            =
                            R xs / ||xs||
                            ×

                            f(||D(Gσ∗I)(x)||)

                    <input class="animation-frames-controls" example="1-1"
                     type="range" value=0 min=0 max=200 step=10>

Example 1 (velocity repairs)

                            Curve velocity
                            is in
                            the outward direction
                            with
                            speed decaying with image edge strength
                            and
                            contracts in bright areas

                            xt
                            =
                            R xs / ||xs||
                            ×

                            f(||D(Gσ∗I)(x)||)
                            ×

                            sign(T-I(x))

                    <input class="animation-frames-controls" example="1-2"
                     type="range" value=0 min=0 max=250 step=10>

Example 2

                            Curve velocity
                            is in
                            the outward direction
                            with
                            speed decaying with image edge strength
                            and
                            contracts in bright areas

                            xt
                            =
                            R xs / ||xs||
                            ×

                            f(||D(Gσ∗I)(x)||)
                            ×

                            sign(T-I(x))

                    <input class="animation-frames-controls" example="2"
                     type="range" value=0 min=0 max=250 step=10>

Implicit curve evolution: level set framework

Implicit curve = {x : u(x,t) = 0}

Enforce level curve moves in normal direction with speed V(x) yields level set evolution PDE: ut + V ||Du|| = 0

[source]

Example 2

                            Velocity in normal direction
                            decays with image edge strength
                            and
                            contracts in bright areas

                            V(x)
                            =

                            f(||D(Gσ∗I)(x)||)
                            ×

                            sign(T-I(x))

                    <input class="animation-frames-controls" example="2-ls"
                     type="range" value=0 min=0 max=1500 step=100>

Some things to read

Kass, Michael, Andrew Witkin, and Demetri Terzopoulos. "Snakes: Active contour models." International journal of computer vision (1988)

Malladi, Ravi, James A. Sethian, and Baba C. Vemuri. "Shape modeling with front propagation: A level set approach." IEEE transactions on pattern analysis and machine intelligence (1995)

Adalsteinsson, David, and James A. Sethian. "A fast level set method for propagating interfaces." Journal of computational physics (1995)


text:
package gui.astar;

import java.util.*;

public interface Node {
    public boolean goalTest(Object o);
    public void printNode();
}


text:
'use strict';

describe('array merge', function(){
  var merge = require('../src/typed_array_merger.js');
  var errors = require('../src/errors.js');

  it('should not be posible to merge with empty array', function () {
    expect(function () {
      merge([]);
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should return same array if only one array to merge', function(){
    var array = new Uint32Array([1,2,3]);
    var toMerge = [ array ];

    var merged = merge(toMerge);

    expect(merged.length).to.equal(array.length);
    for (var i = merged.length - 1; i >= 0; i--) {
      expect(merged[i]).to.equal(array[i]);
    };
  });

  it ('should merge seven arrays', function(){
    var lengths = [0, 1, 2, 100, 200, 500, 1000];

    var toMerge = lengths.map(function(l){
      var r = new Uint32Array(l);
      for (var i = 0; i < l; i++){ r[l] = i; }
      return r;
    });

    var expected_length = lengths.reduce(function(c,v) { return c + v; }, 0);

    var merged = merge(toMerge);

    expect(merged.length).to.equal(expected_length);

    var currentArray = 0, currentSum = 0;

    for (var i = 0; i < expected_length; i++) {
      if (currentSum >= lengths[currentArray]){
        currentSum = 0;
        currentArray++;
      }

      expect(merged[i]).to.equal(toMerge[currentArray][currentSum]);
    };
  })
});


text:
import nconf from '../../config';
import User from '../../models/user';
import Officer from '../../models/officer';

export default function seed() {
  const admin = nconf.get('admin');
  if (admin) {
    return User
      .create(admin)
      .then(user => Officer
          .create({
            title: 'President',
            email: 'president',
            primaryOfficer: true,
            userDce: user.dce,
            startDate: new Date(),
            endDate: new Date(2020, 0, 12),
          }));
  }

  return Promise.resolve();
}


text:
.strengthify-wrapper > * {
	-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
	filter: alpha(opacity=0);
	opacity: 0;
	-webkit-transition:all .5s ease-in-out;
	-moz-transition:all .5s ease-in-out;
	transition:all .5s ease-in-out;
}

.strengthify-bg, .strengthify-container, .strengthify-wrapper, .strengthify-separator {
	height: 3px;
}

.strengthify-bg, .strengthify-container {
	display: block;
	position: absolute;
	width: 100%;
}

.strengthify-bg {
	background-color: #BBB;
}

.strengthify-separator {
	display: inline-block;
	position: absolute;
	background-color: #FFF;
	width: 1px;
	z-index: 10;
}

.password-bad {
	background-color: #C33;
}
.password-medium {
	background-color: #F80;
}
.password-good {
	background-color: #3C3;
}