text:
"""GKE class for creating/reusing a GKE cluster."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import time
import enum
import process_util
import retrying

# Number of times a gcloud CLI should be retried before reporting failure.
_GCLOUD_RETRIES = 1

# Delay (in seconds) between gcloud CLI retries.
_GCLOUD_RETRY_DELAY_SEC = 1

# Number of times a gcloud CLI should be retried before reporting failure.
_KUBECTL_RETRIES = 1

# Delay (in seconds) between gcloud CLI retries.
_KUBECTL_RETRY_DELAY_SEC = 1

# Time we allow a pod stays in initial pending (scheduling) state.
_PENDING_STATE_TIMEOUT_SEC = 20 * 60

@enum.unique
class ClusterStatus(enum.Enum):
  """Enums for GKE cluster status."""
  UNKNOWN = 0
  STATUS_UNSPECIFIED = 1
  PROVISIONING = 2
  RUNNING = 3
  RECONCILING = 4
  STOPPING = 5
  ERROR = 6
  DEGRADED = 7

_CLUSTER_STATUS_MAP = {
    # GKE cluster status from https://goo.gl/Ejieso.
    'STATUS_UNSPECIFIED': ClusterStatus.STATUS_UNSPECIFIED,
    'PROVISIONING': ClusterStatus.PROVISIONING,
    'RUNNING': ClusterStatus.RUNNING,
    'RECONCILING': ClusterStatus.RECONCILING,
    'STOPPING': ClusterStatus.STOPPING,
    'ERROR': ClusterStatus.ERROR,
    'DEGRADED': ClusterStatus.DEGRADED,
}

@enum.unique
class PodStatus(enum.Enum):
  """Enums for kubernetes pod status."""
  UNKNOWN = 0
  FAILED = 1
  PENDING = 2
  RUNNING = 3
  SUCCEEDED = 4

_POD_STATUS_MAP = {
    # Pod status from https://goo.gl/WnSPbQ.
    'Pending': PodStatus.PENDING,
    'Running': PodStatus.RUNNING,
    'Succeeded': PodStatus.SUCCEEDED,
    'Failed': PodStatus.FAILED,
}

def _is_runtime_exception(exception):
  return isinstance(exception, RuntimeError)

class GkeCluster(object):
  """Helper for provisioning GKE cluster."""

  def __init__(self,
               cluster_name,
               cluster_region=None,
               cluster_zone=None,
               alpha_cluster=False,
               create_if_not_exist=True,
               extra_create_args=None):
    """Helper for provisioning GKE cluster.

    On initialization, creates a new cluster or reuses if already exists. Uses
    gcloud's config file implicitly (for determining project, account, and etc).

    Args:
      cluster_name: (str) GKE cluster name. Must be unique within a project.
      cluster_region: (str) GCP region.
      cluster_zone: (str) GCP zone.
      alpha_cluster: (bool) whether the cluster is an alpha cluster.
      create_if_not_exist: (bool) whether to create the cluster if not exists.
      extra_create_args: (list) list of additional args (type str) to be used
          when creating a new cluster. E.g. --num-nodes=1, --enable-tpu, etc.

    Raises:
      ValueError: if both or neither of cluster region and zone is provided.
          Also if zone or region is specified in extra_creare_args.
          Also if cluster_name does not exist and create_if_not_exist is False.
    """
    if not bool(cluster_region) ^ bool(cluster_zone):
      raise ValueError('Either zone or region must be specified for a cluster.')
    if extra_create_args and ('--region' in extra_create_args or
                              '--zone' in extra_create_args):
      raise ValueError('extra_create_args cannot have --zone or --region. '
                       'Specify them explicitly via cluster_region or '
                       'cluster_zone.')

    self._cluster_name = cluster_name
    self._cluster_region = cluster_region
    self._cluster_zone = cluster_zone
    self._alpha_cluster = alpha_cluster
    self._extra_create_args = extra_create_args

    if self._cluster_exists():
      self._reuse_cluster()
    elif create_if_not_exist:
      self._create_cluster()
    else:
      raise ValueError(
          'Cannot create GkeCluster object. GKE cluster %s does not exist, '
          'cannot create GkeCluster object.' % self._cluster_name)

  def _create_cluster(self):
    """Creates a kubernetes cluster.

    Takes care of clean up in case of interruption.

    Raises:
      RuntimeError: if interrupted.
    """
    args = []
    if self._alpha_cluster:
      args = ['gcloud', 'alpha']
    else:
      args = ['gcloud', 'beta']
    args.extend(['container', 'clusters', 'create', self._cluster_name])
    if self._extra_create_args:
      args.extend(self._extra_create_args)

    logging.info('Creating GKE cluster: %s ...', self._cluster_name)
    try:
      self._gcloud_call(args)
    except KeyboardInterrupt:
      logging.error(
          'GKE Cluster creation interrupted. Deallocating the cluster %s ...',
          self._cluster_name)
      self.delete_cluster(wait=False)

  def _reuse_cluster(self):
    """Configures kubernetes tools (kubectl) to use existing cluster.

    Raises:
      RuntimeError: if cluster does not exist or is not reachable.
    """
    self._store_cluster_credentials()
    cluster_status = self._get_cluster_status()
    # Wait for cluster to become ready.
    while cluster_status == ClusterStatus.PROVISIONING:
      time.sleep(_GCLOUD_RETRY_DELAY_SEC)
      cluster_status = self._get_cluster_status()
    if cluster_status in [
        ClusterStatus.STOPPING, ClusterStatus.ERROR, ClusterStatus.DEGRADED
    ]:
      raise RuntimeError('Provided GKE cluster is not reachable. Cluster: %s' %
                         self._cluster_name)

  def _store_cluster_credentials(self):
    """Refreshes credentials for the cluster and stores it in kubectl config.

       See http://goo.gl/cFyUDz for more details.
    """
    args = [
        'gcloud', 'container', 'clusters', 'get-credentials', self._cluster_name
    ]
    logging.info('Storing credential for GKE cluster: %s ...',
                 self._cluster_name)
    self._gcloud_call(args)

  def _get_cluster_status(self):
    """Returns cluster's status."""
    args = [
        'gcloud', 'container', 'clusters', 'describe', self._cluster_name,
        '--format=value(status)'
    ]
    status_str = self._gcloud_call(args).strip()
    if status_str in _CLUSTER_STATUS_MAP:
      return _CLUSTER_STATUS_MAP[status_str]
    return ClusterStatus.UNKNOWN

  def delete_cluster(self, wait=False):
    """Deletes GKE cluster.

    Args:
      wait: (bool) if set blocks on completion.

    Raises:
      ValueError: if cluster does not exist.
      RuntimeError: if fails to delete the cluster.
    """
    if not self._cluster_exists():
      raise ValueError(
          'Cannot delete a non-existent cluster: %s' % self._cluster_name)
    status = self._get_cluster_status()
    if status == ClusterStatus.STOPPING:
      logging.warning(
          'Cannot delete GKE cluster %s. Cluster is being already deleted.',
          self._cluster_name)
      return
    # Cannot delete in PROVISIONING state.
    while status == ClusterStatus.PROVISIONING:
      time.sleep(_GCLOUD_RETRY_DELAY_SEC)
      status = self._get_cluster_status()

    args = [
        'gcloud', 'container', 'clusters', 'delete', self._cluster_name,
        '--quiet'
    ]
    if not wait:
      args = args + ['--async']
    try:
      self._gcloud_call(args)
    except RuntimeError:
      # TODO(b/112040931): create a full link to cluster.
      raise RuntimeError('Failed to delete cluster: %s. Please delete it '
                         'manually on GCP console.' % self._cluster_name)

  def _cluster_exists(self):
    """Returns true iff the cluster exists (not deleted)."""
    args = ['gcloud', 'container', 'clusters', 'list', '--format=value(name)']
    return self._cluster_name in self._gcloud_call(args).splitlines()

  def _gcloud_call(self,
                   args,
                   retry_delay_sec=_GCLOUD_RETRY_DELAY_SEC,
                   retries=_GCLOUD_RETRIES):
    """Make a gcloud CLI call.

    Args:
      args: (list)  A list of arguments (type string) to pass to Popen  call.
      retry_delay_sec: (int) delay in retries.
      retries: (int) number of retries.

    Returns:
      stdout of process call.
    """
    if self._cluster_region:
      args.extend(['--region', self._cluster_region])
    if self._cluster_zone:
      args.extend(['--zone', self._cluster_zone])
    return process_util.run_command(
        args, retry_delay_sec=retry_delay_sec, retries=retries)

  def deploy_pod(self, pod_config, pod_name, retries=0, wait=True):
    """Deploy a pod into Kubernetes cluster.

    Args:
      pod_config: (str) pod config in json format.
      pod_name: (str) Pod's name. Must be the same as the one used in the file.
      retries: (int) retries this number of times if pod status is
        PodStatus.Failure.
      wait: (bool) Whether to wait on completion. If retries is positive, it
        waits on completion regardless.

    Raises:
      RuntimeError: if pod fails or we cannot get its status.
    """
    def get_args(is_first_try=False):
      """Returns kubectl CLI args.

      Args:
        is_first_try: (bool) whether it is the first try.
      """
      if is_first_try:
        return ['kubectl', 'create', '-f', '-']
      else:
        # With replace arg, the pod is first deleted and then re-deployed.
        return ['kubectl', 'replace', '--force', '-f', '-']

    logging.info('Deploying pod %s to GKE cluster %s.', pod_name,
                 self._cluster_name)
    for i in range(retries + 1):
      is_first_try = (i == 0)
      self._kubectl_call(get_args(is_first_try), std_input=pod_config)
      if not wait and not retries:
        return
      curr_pod_status = self._wait_on_state(pod_name, PodStatus.PENDING,
                                            _PENDING_STATE_TIMEOUT_SEC)
      if curr_pod_status == PodStatus.RUNNING:
        curr_pod_status = self._wait_on_state(pod_name, PodStatus.RUNNING)
      if curr_pod_status == PodStatus.SUCCEEDED:
        self.delete_pod(pod_name, wait=True)
        return
      elif i < retries:
        logging.warning(
            'Pod did not suceed. Pod status is %s. Retrying '
            'deploying pod (attempt %d/%d)', curr_pod_status, i + 1, retries)

    self.delete_pod(pod_name, wait=True)
    raise RuntimeError(
        'Pod %s failed after %d attempts.' % (pod_name, retries + 1))

  def _wait_on_state(self, pod_name, state_to_wait_on, timeout=None):
    """Waits as long as the pod is in the given state or timeout reaches.

    Args:
      pod_name: (str) name of the pod.
      state_to_wait_on: (PodStatus) pod's state to wait on.
      timeout: (int) wait at most this many seconds. Both None and 0 mean wait
        forever.

    Returns:
      Latest pod's status.

    Raises:
      RuntimeError if the pod becomes unreachable.
    """
    start_time = time.time()
    state = self.get_pod_status(pod_name)
    while state == state_to_wait_on:
      time.sleep(_KUBECTL_RETRY_DELAY_SEC)
      state = self.get_pod_status(pod_name)
      if timeout and (time.time() - start_time) > timeout:
        break
    return state

  # Retry with a delay between 1 to 10 seconds for at most 100 seconds.
  @retrying.retry(
      retry_on_exception=_is_runtime_exception,
      wait_exponential_multiplier=1000,
      wait_exponential_max=10000,
      stop_max_delay=100000)
  def get_pod_status(self, pod_name):
    """Returns given pod's status.

    Args:
      pod_name: (str) name of pod.
    """
    args = [
        'kubectl', 'get', 'pods', pod_name, '-o', 'jsonpath={.status.phase}'
    ]
    # Retry is done by retry decorator.
    status_str = self._kubectl_call(args, retries=0).strip()
    # When pod fails due to a failure in pulling docker image, we get misleading
    # pending status. See https://github.com/kubernetes/kubernetes/issues/66828
    if status_str == 'Pending' and self._pulling_images_failed(pod_name):
      return PodStatus.FAILED
    return _POD_STATUS_MAP.get(status_str, PodStatus.UNKNOWN)

  def delete_pod(self, pod_name, wait=True):
    """Deletes the given pod.

    Args:
      pod_name: (str) pod's name.
      wait: (bool) whether to wait on completion.
    """
    if not self._pod_exists(pod_name):
      return
    args = ['kubectl', 'delete', 'pod', pod_name]
    if wait:
      args += ['--wait']
      # Retry right away if pod fails and we have already waited for it.
      self._kubectl_call(args, retry_delay_sec=0)
    else:
      self._kubectl_call(args)

  def _pulling_images_failed(self, pod_name):
    """Returns true if there was a failure in pulling docker images.

    Args:
      pod_name: (str) name of pod.
    """
    args = [
        'kubectl', 'get', 'pods', pod_name, '-o',
        'go-template="{{range .status.containerStatuses}}{{if not '
        '.ready}}{{.state.waiting.reason}}{{end}}{{end}}"'
    ]
    containers_status = self._kubectl_call(args, retries=0)
    pull_images_err = ['ImagePullBackOff', 'ErrImagePull']
    return any(err in containers_status for err in pull_images_err)

  def _pod_exists(self, pod_name):
    """Returns true iff the pod exists (not deleted)."""
    args = [
        'kubectl', 'get', 'pods', '-o',
        'jsonpath={.items[*].spec.containers[*].name}'
    ]
    return pod_name in self._kubectl_call(args).split()

  def _kubectl_call(self,
                    args,
                    std_input=None,
                    retry_delay_sec=_KUBECTL_RETRY_DELAY_SEC,
                    retries=_KUBECTL_RETRIES):
    """Make a kubectl CLI call.

    Args:
      args: (list)  A list of arguments (type string) to pass to Popen call.
      std_input: (str) standard input to be passed.
      retry_delay_sec: (int) delay in retries.
      retries: (int) number of retries.

    Returns:
      stdout of process call.

    Raises:
      RuntimeError if process call fails after all retries.
    """
    return process_util.run_command(
        args,
        std_input=std_input,
        retry_delay_sec=retry_delay_sec,
        retries=retries)


text:
.nav li.sfHover,
#tabs ul.wooTabs li a.selected, #tabs ul.wooTabs li a:hover,
.nav a:hover,
.nav li.current_page_item a,
.nav li.current_page_parent a,
.nav li.current-menu-ancestor a,
.nav li.current-menu-item a,
.nav li.sfHover {
    background: #9f9fff;
}

#footer-widgets .block a,
#slides_container .slide .featured-category a,
#slide-nav li a span.info .featured-category { color: #9f9fff; }

#tabs ul.wooTabs li a.selected, #tabs ul.wooTabs li a:hover { color:#4f099e; border-color: #4f099e; }

redpajama_set_name: RedPajamaGithub


text: Tweet


text:
[ -n "$GIT_SUBMODULES_ARE_EVIL" ] && {
    # GIT_SUBMODULES_ARE_EVIL is set, meaning user doesn't want submodules
    echo "Skipping submodules. NUTTX_SRC is set to $NUTTX_SRC"
    exit 0
}

if [ -d NuttX/nuttx ];
	then
	STATUSRETVAL=$(git submodule summary | grep -A20 -i "NuttX" | grep "<")
	if [ -z "$STATUSRETVAL" ]; then
		echo "Checked NuttX submodule, correct version found"
	else
		echo ""
		echo ""
		echo "New commits required:"
		echo "$(git submodule summary)"
		echo ""
		echo ""
		echo "   NuttX sub repo not at correct version. Try 'git submodule update'"
		echo "   or follow instructions on http://pixhawk.org/dev/git/submodules"
		echo ""
		echo "   DO NOT FORGET TO RUN 'make distclean && make archives' AFTER EACH NUTTX UPDATE!"
		exit 1
	fi
else
	git submodule init;
	git submodule update;
fi

if [ -d mavlink/include/mavlink/v1.0 ];
	then
	STATUSRETVAL=$(git submodule summary | grep -A20 -i "mavlink/include/mavlink/v1.0" | grep "<")
	if [ -z "$STATUSRETVAL" ]; then
		echo "Checked mavlink submodule, correct version found"
	else
		echo ""
		echo ""
		echo "New commits required:"
		echo "$(git submodule summary)"
		echo ""
		echo ""
		echo "mavlink sub repo not at correct version. Try 'git submodule update'"
		echo "or follow instructions on http://pixhawk.org/dev/git/submodules"
		exit 1
	fi
else
	git submodule init;
	git submodule update;
fi

if [ -d uavcan ]
then
	STATUSRETVAL=$(git submodule summary | grep -A20 -i uavcan | grep "<")
	if [ -z "$STATUSRETVAL" ]
	then
		echo "Checked uavcan submodule, correct version found"
	else
		echo ""
		echo ""
		echo "New commits required:"
		echo "$(git submodule summary)"
		echo ""
		echo ""
		echo "uavcan sub repo not at correct version. Try 'git submodule update'"
		echo "or follow instructions on http://pixhawk.org/dev/git/submodules"
		exit 1
	fi
else
	git submodule init;
	git submodule update;
fi

if [ -d Tools/gencpp ]
then
	STATUSRETVAL=$(git submodule summary | grep -A20 -i gencpp | grep "<")
	if [ -z "$STATUSRETVAL" ]
	then
		echo "Checked gencpp submodule, correct version found"
	else
		echo ""
		echo ""
		echo "New commits required:"
		echo "$(git submodule summary)"
		echo ""
		echo ""
		echo "gencpp sub repo not at correct version. Try 'git submodule update'"
		echo "or follow instructions on http://pixhawk.org/dev/git/submodules"
		exit 1
	fi
else
	git submodule init;
	git submodule update;
fi

if [ -d Tools/genmsg ]
then
	STATUSRETVAL=$(git submodule summary | grep -A20 -i genmsg | grep "<")
	if [ -z "$STATUSRETVAL" ]
	then
		echo "Checked genmsg submodule, correct version found"
	else
		echo ""
		echo ""
		echo "New commits required:"
		echo "$(git submodule summary)"
		echo ""
		echo ""
		echo "genmsg sub repo not at correct version. Try 'git submodule update'"
		echo "or follow instructions on http://pixhawk.org/dev/git/submodules"
		exit 1
	fi
else
	git submodule init;
	git submodule update;
fi

exit 0


text:
layout: docs
title: codegenFilef
id: interface.Facebook.HackCodegen.ICodegenFactory.codegenFilef
docid: interface.Facebook.HackCodegen.ICodegenFactory.codegenFilef
permalink: /docs/reference/interface.Facebook.HackCodegen.ICodegenFactory.codegenFilef/
---
# Facebook\\HackCodegen\\ICodegenFactory::codegenFilef()

Create a file with the specified filename/path using %-placeholder
format strings

``` Hack
public function codegenFilef(
  HH\Lib\Str\SprintfFormatString $format,
  mixed ...$args,
): Facebook\HackCodegen\CodegenFile;
```

## Parameters

* ` HH\Lib\Str\SprintfFormatString $format `
* ` mixed ...$args `

## Returns

- [` Facebook\HackCodegen\CodegenFile `](<class.Facebook.HackCodegen.CodegenFile.md>)


text:
<?php
require_once("vendor/autoload.php");
use Mike42\WordPuzzles\Cipher;
use Mike42\WordPuzzles\FindAWord;

$cipher = new Cipher;

/* Interface here largely copied from from index.php */
if (has('submit')) {
    if (has('text') && has('lang')) {
        if (has('hint')) {
            $req_hint = true;
        } else {
            $req_hint = false;
        }
        if (has('symbol')) {
            $req_symbol = true;
        } else {
            $req_symbol = false;
        }

        $req_text = take('text');
        if (mb_strlen($req_text) > $cipher -> c_max_len) {
            die("Can't make cryptogram that long.");
        }

        $req_lang= take('lang');
        $fw_lang = FindAWord::supportedLanguages();
        if (!isset($fw_lang[$req_lang])) {
            die("Couldn't find that language!");
        }

        $do = "generate"; /* All info to make puzzle. */
    } else {
        $do = "nothing";
    }
} else {
    $do = "nothing";
}

$page_title    = "Create Word Cipher";
switch ($do) {
    case "nothing":
        $page_script = "cipher-main";
        break;
    case "generate":
        $page_title    = "Word Cipher";
        $cipher -> generateKey('en');
        $cipher -> hint = $req_hint;
        $cipher -> symbol = $req_symbol;
        $cipher -> encode($req_text);
        $page_script = "cipher-generate";
        break;
    default:
        die("Didn't recognise: $do");
}

$page_gen_left = true;
include("includes/page.php");

/* Shorthand for getting request data */
function has($var)
{
    return isset($_REQUEST[$var]);
}
function take($var)
{
    return $_REQUEST[$var];
}


text:
/*
 * =============================================================================
 *
 *       Filename:  rbtree.h
 *
 *    Description:  rbtree(Red-Black tree) implementation adapted from linux
 *                  kernel thus can be used in userspace c program.
 *
 *        Created:  09/02/2012 11:36:11 PM
 *
 *         Author:  Fu Haiping (forhappy), haipingf@gmail.com
 *        Company:  ICT ( Institute Of Computing Technology, CAS )
 *
 * =============================================================================
 */

/*
  Red Black Trees
  (C) 1999  Andrea Arcangeli <andrea@suse.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  linux/include/linux/rbtree.h

  To use rbtrees you'll have to implement your own insert and search cores.
  This will avoid us to use callbacks and to drop drammatically performances.
  I know it's not the cleaner way,  but in C (not in C++) to get
  performances and genericity...

  Some example of insert and search follows here. The search is a plain
  normal search over an ordered tree. The insert instead must be implemented
  in two steps: First, the code must insert the element in order as a red leaf
  in the tree, and then the support library function rb_insert_color() must
  be called. Such function will do the not trivial work to rebalance the
  rbtree, if necessary.

-----------------------------------------------------------------------
static inline struct page * rb_search_page_cache(struct inode * inode,
						 unsigned long offset)
{
	struct rb_node * n = inode->i_rb_page_cache.rb_node;
	struct page * page;

	while (n)
	{
		page = rb_entry(n, struct page, rb_page_cache);

		if (offset < page->offset)
			n = n->rb_left;
		else if (offset > page->offset)
			n = n->rb_right;
		else
			return page;
	}
	return NULL;
}

static inline struct page * __rb_insert_page_cache(struct inode * inode,
						   unsigned long offset,
						   struct rb_node * node)
{
	struct rb_node ** p = &inode->i_rb_page_cache.rb_node;
	struct rb_node * parent = NULL;
	struct page * page;

	while (*p)
	{
		parent = *p;
		page = rb_entry(parent, struct page, rb_page_cache);

		if (offset < page->offset)
			p = &(*p)->rb_left;
		else if (offset > page->offset)
			p = &(*p)->rb_right;
		else
			return page;
	}

	rb_link_node(node, parent, p);

	return NULL;
}

static inline struct page * rb_insert_page_cache(struct inode * inode,
						 unsigned long offset,
						 struct rb_node * node)
{
	struct page * ret;
	if ((ret = __rb_insert_page_cache(inode, offset, node)))
		goto out;
	rb_insert_color(node, &inode->i_rb_page_cache);
 out:
	return ret;
}
-----------------------------------------------------------------------
*/

#ifndef	_LINUX_RBTREE_H
#define	_LINUX_RBTREE_H

#if defined(container_of)
  #undef container_of
  #define container_of(ptr, type, member) ({			\
        const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
        (type *)( (char *)__mptr - offsetof(type,member) );})
#else
  #define container_of(ptr, type, member) ({			\
        const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
        (type *)( (char *)__mptr - offsetof(type,member) );})
#endif

#if defined(offsetof)
  #undef offsetof
  #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#else
  #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#undef NULL
#if defined(__cplusplus)
  #define NULL 0
#else
  #define NULL ((void *)0)
#endif

struct rb_node
{
	unsigned long  rb_parent_color;
#define	RB_RED		0
#define	RB_BLACK	1
	struct rb_node *rb_right;
	struct rb_node *rb_left;
} __attribute__((aligned(sizeof(long))));
    /* The alignment might seem pointless, but allegedly CRIS needs it */

struct rb_root
{
	struct rb_node *rb_node;
};

#define rb_parent(r)   ((struct rb_node *)((r)->rb_parent_color & ~3))
#define rb_color(r)   ((r)->rb_parent_color & 1)
#define rb_is_red(r)   (!rb_color(r))
#define rb_is_black(r) rb_color(r)
#define rb_set_red(r)  do { (r)->rb_parent_color &= ~1; } while (0)
#define rb_set_black(r)  do { (r)->rb_parent_color |= 1; } while (0)

static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)
{
	rb->rb_parent_color = (rb->rb_parent_color & 3) | (unsigned long)p;
}
static inline void rb_set_color(struct rb_node *rb, int color)
{
	rb->rb_parent_color = (rb->rb_parent_color & ~1) | color;
}

#define RB_ROOT	(struct rb_root) { NULL, }
#define	rb_entry(ptr, type, member) container_of(ptr, type, member)

#define RB_EMPTY_ROOT(root)	((root)->rb_node == NULL)
#define RB_EMPTY_NODE(node)	(rb_parent(node) == node)
#define RB_CLEAR_NODE(node)	(rb_set_parent(node, node))

static inline void rb_init_node(struct rb_node *rb)
{
	rb->rb_parent_color = 0;
	rb->rb_right = NULL;
	rb->rb_left = NULL;
	RB_CLEAR_NODE(rb);
}

extern void rb_insert_color(struct rb_node *, struct rb_root *);
extern void rb_erase(struct rb_node *, struct rb_root *);

typedef void (*rb_augment_f)(struct rb_node *node, void *data);

extern void rb_augment_insert(struct rb_node *node,
			      rb_augment_f func, void *data);
extern struct rb_node *rb_augment_erase_begin(struct rb_node *node);
extern void rb_augment_erase_end(struct rb_node *node,
				 rb_augment_f func, void *data);

/* Find logical next and previous nodes in a tree */
extern struct rb_node *rb_next(const struct rb_node *);
extern struct rb_node *rb_prev(const struct rb_node *);
extern struct rb_node *rb_first(const struct rb_root *);
extern struct rb_node *rb_last(const struct rb_root *);

/* Fast replacement of a single node without remove/rebalance/add/rebalance */
extern void rb_replace_node(struct rb_node *victim, struct rb_node *new,
			    struct rb_root *root);

static inline void rb_link_node(struct rb_node * node, struct rb_node * parent,
				struct rb_node ** rb_link)
{
	node->rb_parent_color = (unsigned long )parent;
	node->rb_left = node->rb_right = NULL;

	*rb_link = node;
}

#endif	/* _LINUX_RBTREE_H */


text:
"""
The ``ui.VerticalPanel`` class is a panel that lays out its contents from top
to bottom.

It is often useful to call ``setSpacing(spacing)`` to add space between each of
the panel's widgets.  You can also call ``setHorizontalAlignment(alignment)``
and ``setVerticalAlignment(alignment)`` before adding widgets to control how
those widgets are aligned within the available space.  Alternatively, you can
call ``setCellHorizontalAlignment(widget, alignment)`` and
``setCellVerticalAlignment(widget, alignment)`` to change the alignment of a
single widget after it has been added.

Note that if you want to have different widgets within the panel take up
different amounts of space, don't call ``widget.setWidth(width)`` or
``widget.setHeight(height)`` as these are ignored by the panel.  Instead, call
``panel.setCellWidth(widget, width)`` and ``panel.setCellHeight(widget,
height)``.
"""
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.Label import Label
from pyjamas.ui import HasAlignment

class VerticalPanelDemo(SimplePanel):
    def __init__(self):
        SimplePanel.__init__(self)

        panel = VerticalPanel()
        panel.setBorderWidth(1)

        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)

        part1 = Label("Part 1")
        part2 = Label("Part 2")
        part3 = Label("Part 3")
        part4 = Label("Part 4")

        panel.add(part1)
        panel.add(part2)
        panel.add(part3)
        panel.add(part4)

        panel.setCellHeight(part1, "10%")
        panel.setCellHeight(part2, "70%")
        panel.setCellHeight(part3, "10%")
        panel.setCellHeight(part4, "10%")

        panel.setCellHorizontalAlignment(part3, HasAlignment.ALIGN_RIGHT)

        panel.setWidth("50%")
        panel.setHeight("300px")

        self.add(panel)


text:
package com.tle.core.hibernate.impl;

import com.tle.core.hibernate.ExtendedAnnotationConfiguration;
import com.tle.core.hibernate.ExtendedDialect;
import com.tle.core.hibernate.HibernateFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.classic.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.Mapping;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.AuxiliaryDatabaseObject;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Index;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.UniqueKey;

@SuppressWarnings("nls")
public class HibernateMigrationHelper {
  private final Dialect dialect;
  private final ExtendedDialect extDialect;
  private final String defaultCatalog;
  private final String defaultSchema;
  private final Mapping mapping;
  private final ExtendedAnnotationConfiguration configuration;
  private final SessionFactoryImpl factory;

  private static final Log LOGGER = LogFactory.getLog(HibernateMigrationHelper.class);

  public HibernateMigrationHelper(HibernateFactory factory) {
    this(factory, factory.getDefaultSchema());
  }

  public HibernateMigrationHelper(HibernateFactory factory, String defaultSchema) {
    this.factory = (SessionFactoryImpl) factory.getSessionFactory();
    dialect = this.factory.getDialect();
    extDialect = (ExtendedDialect) dialect;
    this.configuration = factory.getConfiguration();
    mapping = configuration.buildMapping();
    this.defaultSchema = defaultSchema;
    defaultCatalog = null;
  }

  public List<String> getDropTableSql(String... tables) {
    List<String> drops = new ArrayList<String>();
    for (String tableName : tables) {
      Table table = findTable(tableName);
      drops.add(table.sqlDropString(dialect, defaultCatalog, defaultSchema));
    }
    return drops;
  }

  @SuppressWarnings("unchecked")
  public List<String> getCreationSql(HibernateCreationFilter filter) {
    List<String> sqlStrings = new ArrayList<String>();
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Tables registered:" + configuration.getTableMap().keySet());
    }
    for (Table table : configuration.getTableMap().values()) {
      if (table.isPhysicalTable() && filter.includeTable(table)) {
        sqlStrings.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
      }
    }

    for (Table table : configuration.getTableMap().values()) {
      if (table.isPhysicalTable()) {

        Iterator<Index> subIter = table.getIndexIterator();
        while (subIter.hasNext()) {
          Index index = subIter.next();
          if (filter.includeIndex(table, index)
              && (!extDialect.supportsAutoIndexForUniqueColumn()
                  || !hasUniqueIndex(index, table))) {
            sqlStrings.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
          }
        }

        if (dialect.hasAlterTable()) {
          Iterator<ForeignKey> forIter = table.getForeignKeyIterator();
          while (forIter.hasNext()) {
            ForeignKey fk = forIter.next();
            if (fk.isPhysicalConstraint() && filter.includeForeignKey(table, fk)) {
              sqlStrings.add(fk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }
          }
        }
      }
    }
    Collection<PersistentIdentifierGenerator> generators =
        configuration.getGenerators(dialect, defaultCatalog, defaultSchema);
    for (PersistentIdentifierGenerator pig : generators) {
      if (filter.includeGenerator(pig)) {
        String[] lines = pig.sqlCreateStrings(dialect);
        Collections.addAll(sqlStrings, lines);
      }
    }

    for (AuxiliaryDatabaseObject object : configuration.getAuxiliaryDatabaseObjects()) {
      if (object.appliesToDialect(dialect) && filter.includeObject(object)) {
        sqlStrings.add(object.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
      }
    }
    return sqlStrings;
  }

  public List<String> getAddColumnsSQL(String tableName, String... columnNames) {
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    for (String columnName : columnNames) {
      Column column = table.getColumn(new Column(columnName));

      StringBuffer alter =
          new StringBuffer("alter table ")
              .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
              .append(' ')
              .append(dialect.getAddColumnString());
      alter
          .append(' ')
          .append(column.getQuotedName(dialect))
          .append(' ')
          .append(column.getSqlType(dialect, mapping));

      boolean useUniqueConstraint =
          extDialect.supportsModifyWithConstraints()
              && column.isUnique()
              && dialect.supportsUnique()
              && (!column.isNullable() || dialect.supportsNotNullUnique());
      if (useUniqueConstraint) {
        alter.append(" unique");
      }
      if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
        alter.append(" check(").append(column.getCheckConstraint()).append(")");
      }

      String columnComment = column.getComment();
      if (columnComment != null) {
        alter.append(dialect.getColumnComment(columnComment));
      }
      sqlStrings.add(alter.toString());
    }
    return sqlStrings;
  }

  /**
   * By default we assume that foreign key constraints will be added for the columnNames
   *
   * @param tableName
   * @param columnNames
   * @return
   */
  public List<String> getAddIndexesAndConstraintsForColumns(
      String tableName, String... columnNames) {
    return getAddIndexesAndConstraintsForColumns(tableName, true, columnNames);
  }

  @SuppressWarnings({"unchecked"})
  public List<String> getAddIndexesAndConstraintsForColumns(
      String tableName, boolean includeForeignKeyConstraints, String... columnNames) {
    Set<Column> colSet = new HashSet<Column>();
    for (String columnName : columnNames) {
      colSet.add(new Column(columnName));
    }
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    if (!extDialect.supportsModifyWithConstraints()) {
      for (Column col : colSet) {
        Column realCol = table.getColumn(col);
        if (realCol.isUnique()) {
          table.createUniqueKey(Collections.singletonList(realCol));
        }
      }
    }
    Iterator<UniqueKey> keyIter = table.getUniqueKeyIterator();
    if (dialect.supportsUniqueConstraintInCreateAlterTable()) {
      while (keyIter.hasNext()) {
        UniqueKey uk = keyIter.next();
        if (!Collections.disjoint(uk.getColumns(), colSet)) {
          StringBuilder buf = new StringBuilder("alter table ");
          buf.append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema));
          buf.append(" add constraint ");
          buf.append(extDialect.getRandomIdentifier());
          buf.append(' ');
          String constraint = uk.sqlConstraintString(dialect);
          if (constraint != null) {
            buf.append(constraint);
            sqlStrings.add(buf.toString());
          }
        }
      }
    } else {
      while (keyIter.hasNext()) {
        UniqueKey ukey = keyIter.next();
        if (!Collections.disjoint(ukey.getColumns(), colSet)) {
          sqlStrings.add(ukey.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        }
      }
    }

    addIndexSQL(sqlStrings, table, colSet);

    // Caller may opt to skip foreign key constraints
    if (includeForeignKeyConstraints) {
      Iterator<ForeignKey> fkeyIter = table.getForeignKeyIterator();
      while (fkeyIter.hasNext()) {
        ForeignKey fkey = fkeyIter.next();
        if (!Collections.disjoint(fkey.getColumns(), colSet)) {
          sqlStrings.add(fkey.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        }
      }
    }

    return sqlStrings;
  }

  public List<String> getAddIndexesForColumns(String tableName, String... columnNames) {
    Set<Column> colSet = new HashSet<Column>();
    for (String columnName : columnNames) {
      colSet.add(new Column(columnName));
    }
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    addIndexSQL(sqlStrings, table, colSet);
    return sqlStrings;
  }

  @SuppressWarnings({"unchecked"})
  private void addIndexSQL(List<String> sqlStrings, Table table, Set<Column> colSet) {
    Iterator<Index> indexIterator = table.getIndexIterator();
    while (indexIterator.hasNext()) {
      Index index = indexIterator.next();
      Iterator<Column> colIter = index.getColumnIterator();
      boolean found = false;
      while (colIter.hasNext()) {
        Column col = colIter.next();
        if (colSet.contains(col)) {
          found = true;
          break;
        }
      }
      if (found
          && (!extDialect.supportsAutoIndexForUniqueColumn() || !hasUniqueIndex(index, table))) {
        sqlStrings.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
      }
    }
  }

  public String getAddNamedIndex(String tableName, String indexName, String... columnNames) {
    Index index = new Index();
    index.setName(indexName);
    index.setTable(findTable(tableName));
    for (String columnName : columnNames) {
      index.addColumn(new Column(columnName));
    }
    return index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
  }

  public String getDropNamedIndex(String tableName, String indexName) {
    return extDialect.getDropIndexSql(tableName, indexName);
  }

  @SuppressWarnings("unchecked")
  private boolean hasUniqueIndex(Index index, Table table) {
    HashSet<Column> indexCols = new HashSet<Column>();
    Iterator<Column> icolIter = index.getColumnIterator();
    while (icolIter.hasNext()) {
      Column col = icolIter.next();
      indexCols.add(col);
      if (index.getColumnSpan() == 1 && table.getColumn(col).isUnique()) {
        return true;
      }
    }
    Iterator<UniqueKey> iter = table.getUniqueKeyIterator();
    while (iter.hasNext()) {
      UniqueKey uk = iter.next();
      if (uk.getColumnSpan() == indexCols.size() && indexCols.containsAll(uk.getColumns())) {
        return true;
      }
    }
    return false;
  }

  /**
   * @param tableName
   * @param columnName
   * @param changeNotNull
   * @param nullable Pass in null to use the annotation on the column. This is not always possible
   *     (see Redmine #3329).
   * @param changeType
   * @return
   */
  public List<String> getModifyColumnSQL(
      String tableName, String columnName, boolean changeNotNull, boolean changeType) {
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    Column column = table.getColumn(new Column(columnName));

    StringBuffer alter =
        new StringBuffer("alter table ")
            .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
            .append(' ')
            .append(extDialect.getModifyColumnSql(mapping, column, changeNotNull, changeType));

    sqlStrings.add(alter.toString());
    return sqlStrings;
  }

  public boolean tableExists(Session session, final String table) {
    final ExtendedDialect locDialect = (ExtendedDialect) this.dialect;
    final Boolean[] hasTable = new Boolean[1];
    session.doWork(
        new Work() {

          @Override
          public void execute(Connection connection) throws SQLException {
            ResultSet tables =
                connection
                    .getMetaData()
                    .getTables(
                        null,
                        defaultSchema,
                        locDialect.getNameForMetadataQuery(table, false),
                        new String[] {"TABLE"});
            try {
              hasTable[0] = tables.next();
            } finally {
              tables.close();
            }
          }
        });
    return hasTable[0];
  }

  public List<String> getDropColumnSQL(String tableName, String... columns) {
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    for (String columnName : columns) {
      Column column = table.getColumn(new Column(columnName));
      if (column == null) {
        throw new RuntimeException(
            "Could not find column " + columnName + " on table " + tableName);
      }
      sqlStrings.add(
          extDialect.getDropColumnSql(
              table.getQualifiedName(dialect, defaultCatalog, defaultSchema), column));
    }
    return sqlStrings;
  }

  public List<String> getAddNotNullSQL(String tableName, String... columns) {
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);
    for (String columnName : columns) {
      Column column = table.getColumn(new Column(columnName));

      StringBuffer alter =
          new StringBuffer("alter table ")
              .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
              .append(' ')
              .append(extDialect.getAddNotNullSql(mapping, column));
      sqlStrings.add(alter.toString());
    }
    return sqlStrings;
  }

  public List<String> getRenameColumnSQL(
      String tableName, String columnName, String newColumnName) {
    List<String> sqlStrings = new ArrayList<String>();

    Table table = findTable(tableName);

    Column column = table.getColumn(new Column(columnName));
    String alter = null;
    alter =
        extDialect.getRenameColumnSql(
            table.getQualifiedName(dialect, defaultCatalog, defaultSchema), column, newColumnName);
    sqlStrings.add(alter);

    return sqlStrings;
  }

  public String getQuotedIdentifier(String ident) {
    return dialect.openQuote() + ident + dialect.closeQuote();
  }

  public String getDefaultCatalog() {
    return defaultCatalog;
  }

  public String getDefaultSchema() {
    return defaultSchema;
  }

  public SessionFactoryImpl getFactory() {
    return factory;
  }

  public ExtendedDialect getExtDialect() {
    return extDialect;
  }

  public List<String> getAddNotNullSQLIfRequired(
      Session session, String tableName, String... columns) {
    final Table table = findTable(tableName);

    final List<String> sqlStrings = new ArrayList<String>();
    final Set<String> colset = new HashSet<String>(Arrays.asList(columns));
    session.doWork(
        new Work() {
          @Override
          public void execute(Connection connection) throws SQLException {
            ResultSet colresult =
                connection
                    .getMetaData()
                    .getColumns(
                        getDefaultCatalog(),
                        extDialect.getNameForMetadataQuery(getDefaultSchema(), false),
                        extDialect.getNameForMetadataQuery(table.getName(), table.isQuoted()),
                        "%");
            try {
              while (colresult.next()) {
                String columnName = colresult.getString("COLUMN_NAME").toLowerCase();
                if (colset.contains(columnName)
                    && "yes".equals(colresult.getString("IS_NULLABLE").toLowerCase())) {
                  Column column = table.getColumn(new Column(columnName));

                  StringBuffer alter =
                      new StringBuffer("alter table ")
                          .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                          .append(' ')
                          .append(extDialect.getAddNotNullSql(mapping, column));
                  sqlStrings.add(alter.toString());
                }
              }
            } finally {
              colresult.close();
            }
          }
        });
    return sqlStrings;
  }

  @SuppressWarnings("unchecked")
  public Collection<? extends String> getAddIndexesIfRequired(
      Session session, String tableName, String... indexes) {
    final Table table = findTable(tableName);

    List<String> sqlStrings = new ArrayList<String>();
    Map<Set<String>, String> revIndexMap = getExistingIndexes(table, session);
    Set<String> indexSet = new HashSet<String>(Arrays.asList(indexes));
    Iterator<Index> indexIterator = table.getIndexIterator();
    while (indexIterator.hasNext()) {
      Index index = indexIterator.next();
      if (!indexSet.remove(index.getName())) {
        continue;
      }
      processIndex(table, index, revIndexMap, sqlStrings);
    }
    if (!indexSet.isEmpty()) {
      throw new RuntimeException("Failed to find indexes:" + indexSet + " on table: " + tableName);
    }
    return sqlStrings;
  }

  public Collection<? extends String> getAddIndexesRawIfRequired(
      Session session, String tableName, String indexName, String indexColumn) {
    return getAddIndexesRawIfRequired(session, tableName, new String[] {indexName, indexColumn});
  }

  public Collection<? extends String> getAddIndexesRawIfRequired(
      Session session, String tableName, String[]... indexes) {
    List<String> sqlStrings = new ArrayList<String>();
    final Table table = findTable(tableName);
    Map<Set<String>, String> revIndexMap = getExistingIndexes(table, session);
    for (String[] index : indexes) {
      Index indexObj = new Index();
      indexObj.setTable(table);
      indexObj.setName(index[0]);
      for (int i = 1; i < index.length; i++) {
        Column col = new Column(index[i]);
        indexObj.addColumn(col);
      }
      processIndex(table, indexObj, revIndexMap, sqlStrings);
    }
    return sqlStrings;
  }

  public Collection<? extends String> getAddIndexesRaw(
      String tableName, String indexeName, String indexColumn) {
    return getAddIndexesRaw(tableName, new String[] {indexeName, indexColumn});
  }

  public Collection<? extends String> getAddIndexesRaw(String tableName, String[]... indexes) {
    List<String> sqlStrings = new ArrayList<String>();
    final Table table = findTable(tableName);
    for (String[] index : indexes) {
      Index indexObj = new Index();
      indexObj.setTable(table);
      indexObj.setName(index[0]);
      for (int i = 1; i < index.length; i++) {
        Column col = new Column(index[i]);
        indexObj.addColumn(col);
      }
      sqlStrings.add(indexObj.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
    }
    return sqlStrings;
  }

  /**
   * Variation on getAddIndexesRaw, whereby we pass it to the ExtendedDialect subclass(es) to custom
   * knit a function call around all the column names, hence for example instead of indexing
   * TLEUser.username, we want to index lower(TLEUser.username).
   *
   * @param tableName
   * @param indexes
   * @return
   */
  public Collection<? extends String> getAddFunctionIndexes(
      String tableName, String function, String[]... indexes) {
    List<String> sqlStrings = new ArrayList<String>();

    for (String[] indexableColumns : indexes) {
      sqlStrings.addAll(extDialect.getCreateFunctionalIndex(tableName, function, indexableColumns));
    }
    return sqlStrings;
  }

  @SuppressWarnings("unchecked")
  private void processIndex(
      Table table, Index index, Map<Set<String>, String> revIndexMap, List<String> sqlStrings) {
    Iterator<Column> colIter = index.getColumnIterator();
    Set<String> indexCols = new HashSet<String>();
    while (colIter.hasNext()) {
      Column col = colIter.next();
      indexCols.add(col.getName().toLowerCase());
    }
    String existingIndex = revIndexMap.get(indexCols);
    if (existingIndex != null) {
      if (existingIndex.equalsIgnoreCase(index.getName())) {
        return;
      } else {
        sqlStrings.add(extDialect.getDropIndexSql(table.getName(), '`' + existingIndex + '`'));
      }
    }
    sqlStrings.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
  }

  public Map<Set<String>, String> getExistingIndexes(final Table table, Session session) {
    final Map<String, Set<String>> indexMap = new HashMap<String, Set<String>>();

    // Query existing index
    session.doWork(
        new Work() {
          @Override
          public void execute(Connection connection) throws SQLException {
            ResultSet colresult =
                connection
                    .getMetaData()
                    .getIndexInfo(
                        getDefaultCatalog(),
                        extDialect.getNameForMetadataQuery(getDefaultSchema(), false),
                        extDialect.getNameForMetadataQuery(table.getName(), table.isQuoted()),
                        false,
                        false);
            try {
              while (colresult.next()) {
                String indexName = colresult.getString("INDEX_NAME");
                String columnName = colresult.getString("COLUMN_NAME");
                if (columnName != null) {
                  columnName = columnName.toLowerCase();
                  Set<String> cols = indexMap.get(indexName);
                  if (cols == null) {
                    cols = new HashSet<String>();
                    indexMap.put(indexName, cols);
                  }
                  cols.add(columnName);
                }
              }
            } finally {
              colresult.close();
            }
          }
        });
    // Change from (index -> cols) to (cols -> index)
    Map<Set<String>, String> revIndexMap = new HashMap<Set<String>, String>();
    for (Map.Entry<String, Set<String>> entry : indexMap.entrySet()) {
      revIndexMap.put(entry.getValue(), entry.getKey());
    }
    return revIndexMap;
  }

  private Table findTable(String tableName) {
    Map<String, Table> tableMap = configuration.getTableMap();
    Table table = tableMap.get(tableName);
    if (table == null) {
      throw new RuntimeException("Failed to find table: " + tableName);
    }
    return table;
  }

  public List<String> getDropConstraintsSQL(String table, String... columnNames) {
    List<String> sql = new ArrayList<String>();
    for (String columnName : columnNames) {
      sql.add(extDialect.getDropConstraintsForColumnSql(table, columnName));
    }
    return sql;
  }
}


text:
title: Control Flow
---
# Control Flow

Control flow statements are exactly what the term means. They are statements that alter execution flow based on decisions, loops and branching so that the program can conditionally execute blocks of code.

Primarily, Java has the following constructs for flow control:

*   `if`
    ```java
    if( <expression that results in a boolean> ){
        //code enters this block if the above expression is 'true'
    }
    ```

*   `if...else`
    ```java
    if( <expression that results in a boolean> ){
        //execute this block if the expression is 'true'
    } else{
        //execute this block if the expression is 'false'
    }
    ```

*   `switch`

Switch is an alternative for the `if...else` construct when there are multiple values and cases to check against.

```java
switch( <integer / String / Enum > ){
    case <int/String/Enum>:
        <statements>
        break;
    case <int/String/Enum>:
        <statements>
        break;
    default:
        <statements>
}
```

Note: The program flow `falls through` the next `case` if the `break` statement is missing. e.g. Let's say you say the standard 'Hello' to everyone at office, but you are extra nice to the girl who sits next to you and sound grumpy to your boss. The way to represent would be something like:
```java
switch(person){
    case 'boss':
        soundGrumpy();
        break;
    case 'neighbour':
        soundExtraNice();
        break;
    case 'colleague':
        soundNormal();
        break;
    default:
        soundNormal();
}
```

    Note: The `default` case runs when none of the `case` matches. Remember that when a case has no `break` statement, it `falls through` to the next case and will continue to the subsequent `cases` till a `break` is encountered. Because of this, make sure that each case has a `break` statement. The `default` case does not require a `break` statement.

*   `nested statements`

Any of the previous control flows can be nested. Which means you can have nested `if`,`if..else`and`switch..case`statements. i.e., you can have any combination of these statements within the other and there is no limitation to the depth of`nesting`.

For example, let's consider the following scenario:

*   If you have less than 25 bucks, you get yourself a cup of coffee.
*   If you have more than 25 bucks but less than 60 bucks, you get yourself a decent meal.
*   If you have more than 60 bucks but less than a 100, you get yourself a decent meal along with a glass of wine.
*   However, when you have more than a 100 bucks, depending on who you are with, you either go for a candle lit dinner (with your wife) or you go to a sports bar (with your friends).

One of the ways to represent this will be:

```java
int cash = 150;
String company = "friends";

if( cash < 25 ){
    getCoffee();
} else if( cash < 60 ){
    getDecentMeal();
} else if( cash < 100 ){
    getDecentMeal();
    getGlassOfWine();
} else {
    switch(company){
        case "wife":
            candleLitDinner();
            break;
        case "friends":
            meetFriendsAtSportsBar();
            break;
        default:
            getDecentMeal();
    }
}
```
In this example, `meetFriendsAtSportsBar()` will be executed.

![:rocket:](https://forum.freecodecamp.org/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") Run Code


text:
package org.datasays.wes.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by watano on 2016/12/4.
 */
public class JsonObj extends LinkedHashMap<String, Object> {

	public JsonObj() {
		super();
	}

	public JsonObj(Object... allkv) {
		super();
		this.addAll(allkv);
	}

	public void addAll(Object... allkv) {
		if (allkv != null && allkv.length % 2 == 0) {
			for (int i = 0; i + 1 < allkv.length; i += 2) {
				put(allkv[i].toString(), allkv[i + 1]);
			}
		}
	}

	public void lstAdd(String key, Object... values) {
		Object v = get(key);
		Object[] allValue = values;
		if(allValue == null){
			allValue = new Object[]{};
		}
		if (v == null) {
			put(key, values);
		} else if (v instanceof Object[]) {
			Object[] vs = (Object[]) v;
			List<Object> all = new ArrayList<>();
			all.addAll(Arrays.asList(vs));
			for (Object value : values) {
				all.add(value);
			}
			put(key, all.toArray(new Object[]{}));
		} else {
			List<Object> all = new ArrayList<>();
			all.addAll(Arrays.asList(values));
			all.add(0, v);
			put(key, all.toArray(new Object[]{}));
		}
	}

	public void putWithoutNull(String key, Object value) {
		if (value != null) {
			put(key, value);
		}
	}

	public void put(String key, Object value, Object defaultValue) {
		if (value == null && defaultValue != null) {
			put(key, defaultValue);
			return;
		}
		put(key, value);
	}

	public void putInto(String key, Object vlaue, String... parents) {
		JsonObj pMap = this;
		for (String parent : parents) {
			Object pObj = pMap.get(parent);
			if (pObj != null && pObj instanceof JsonObj) {
				pMap = (JsonObj) pObj;
			}
		}
		pMap.put(key, vlaue);
	}

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = {
    TRAIN_BEGIN: 'TRAIN_BEGIN',
    EPOCH_BEGIN: 'EPOCH_BEGIN',
    BATCH_END: 'BATCH_END',
    EPOCH_END: 'EPOCH_END',
    TRAIN_END: 'TRAIN_END'
};


text:
var db          = require('../db.js');
var Promise     = require('bluebird');
var General     = require('../lib/general.js');
var Group       = module.exports = General.access('groups')


text:
package squants.time

import org.scalatest.{ Matchers, FlatSpec }
import squants.CustomMatchers

/**
 * @author  garyKeorkunian
 * @since   0.5.1
 *
 */
class TimeSquaredSpec extends FlatSpec with Matchers with CustomMatchers {

  behavior of "Time Squared as an intermediate operand in time derivative calculations"

  it should "create values in the correct units" in {
    SecondsSquared(10) should be(TimeSquared(Seconds(10), Seconds(10)))
    MinutesSquared(10) should be(TimeSquared(Minutes(10), Minutes(10)))
    HoursSquared(10) should be(TimeSquared(Hours(10), Hours(10)))
    TimeSquared(Seconds(5)) should be(TimeSquared(Seconds(5), Seconds(5)))
  }
}