text:
package com.intellij.psi.impl.source;

import com.intellij.util.CharTable;
import org.jetbrains.annotations.NotNull;

/*
 * User: max
 * Date: Sep 16, 2006
 */
public class IdentityCharTable implements CharTable {
  private IdentityCharTable() { }

  public static final IdentityCharTable INSTANCE = new IdentityCharTable();

  @NotNull
  @Override
  public CharSequence intern(@NotNull final CharSequence text) {
    return text;
  }

  @NotNull
  @Override
  public CharSequence intern(@NotNull CharSequence baseText, int startOffset, int endOffset) {
    if (startOffset == 0  && endOffset == baseText.length()) return baseText;
    return baseText.subSequence(startOffset, endOffset);
  }
}

redpajama_set_name: RedPajamaGithub


text:
Se necesita crear una aplicación Web, que tenga un módulo de formulario Web, y un módulo de Administración Web.

Herramientas:
-------------
- GIT
- Eclipse Kepler o superior
- Proyecto base Github
- Base de Datos SQLite3
- Hibernate
- JavaServer Pages
- JBoss AS 7.1.1

Módulo de formulario:
-------------
###Se debe crear un formulario que contenga lo siguientes elementos:######
- Primer nombre
- Segundo nombre
- Apellido paterno
- Apellido materno
- Fecha de Nacimiento
- Sexo: Si la persona es del sexo femenino, debe habilitarse una opción ("checkbox"), que indique si esa persona tiene apellido de casada, de ser así, habilitar el textbox para que pueda introducir su apellido de casada
- Lugar de residencia (textarea)
- Teléfono
- Email
- Botón para limpiar todos los campos
- Botón para guardar el formulario

Módulo de Administración:
-------------
- Crear un módulo de Administración que debe permitir con un botón mostrar el listado de usuarios registrados ordenados por cédula de forma descendente, solo debe mostrar la cédula y el nombre completo de la persona.
- Opción de búsqueda, donde pueda permitir al Administrador introducir una cédula y que devuelva el sitio web toda la información de la cédula introducida.

####Parámetros de salida:########
- Mostrar Primer Nombre y Segundo nombre de la persona concatenado en un solo resultado.
- Devolver el Apellido Paterno y Materno de la persona concatenado y dependiendo si selecciono que tiene Apellido Casada, concatenar el apellido casada.
- Mostrar Fecha de nacimiento de la persona en formato dd/mm/yyyy. Ejemplo (19/09/1982)
- Mostrar Teléfono
- Mostrar Email
- Crear Base de Datos en SQLite3.
- Crear Tabla/s en la Base de Datos, con los datos requeridos en la aplicación.


text:
namespace ash::string_matching {

// These are described in more detail in the .cc file.
// The namespace is to distinguish from the constants in prefix matcher.
namespace acronym_matcher_constants {

constexpr double kIsPrefixCharScore = 1.0;
constexpr double kIsFrontOfTokenCharScore = 0.8;

constexpr double kNoMatchScore = 0.0;

}  // namespace acronym_matcher_constants

// AcronymMatcher matches the chars of a given query as acronym of tokens in
// a given text. i.e. To capture the information that:
// With the text "axx bxx cxx", queries "a", "ab", "abc", "b", "bc" and "c" are
// all considered as acronym matching to the text, while queries "abcd", "ab c",
// and "abdc" are not.
class AcronymMatcher {
 public:
  AcronymMatcher(const TokenizedString& query, const TokenizedString& text);
  ~AcronymMatcher();

  AcronymMatcher(const AcronymMatcher&) = delete;
  AcronymMatcher& operator=(const AcronymMatcher&) = delete;

  // Perform acronym match. Stops on the first full match
  // and returns true. Otherwise, returns false to indicate no match.
  double CalculateRelevance();

 private:
  std::u16string query_;
  std::u16string text_acronym_;
};

}  // namespace ash::string_matching

#endif  // CHROMEOS_ASH_COMPONENTS_STRING_MATCHING_ACRONYM_MATCHER_H_


text:
<?php

namespace Asoc\Dadatata\Filter\ImageMagick;

use Asoc\Dadatata\Exception\ProcessingFailedException;
use Asoc\Dadatata\Filter\BaseMagickFilter;
use Asoc\Dadatata\Filter\ImageOptions;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ImageInterface;
use Asoc\Dadatata\Model\ThingInterface;

class Resize extends BaseMagickFilter
{
    /**
     * @param ThingInterface|ImageInterface $thing
     * @param string                        $sourcePath
     * @param OptionsInterface|ImageOptions $options
     *
     * @throws \Asoc\Dadatata\Exception\ProcessingFailedException
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $tmpPath = tempnam(sys_get_temp_dir(), 'Dadatata');

        $options = $this->defaults->merge($options);

        $pb = $this->getConvertProcess();
        $pb->add('-quality')->add($options->getQuality());

        $width  = $options->getWidth();
        $height = $options->getHeight();

        list($resizeRatio, $width, $height) = $this->getProperSize(
            $width,
            $height,
            $thing->getWidth(),
            $thing->getHeight()
        );

        // only perform a resize when width and/or height changed
        if ($thing->getWidth() !== $width || $thing->getHeight() !== $height) {
            $pb->add('-resize')->add(sprintf('%dx%d', $width, $height));
        }

        $pb->add(sprintf('%s[0]', $sourcePath));
        $pb->add(sprintf('%s:%s', $options->getFormat(), $tmpPath));

        $process = $pb->getProcess();
        $code    = $process->run();

        if ($code !== 0) {
            throw ProcessingFailedException::create(
                'Failed to resize image',
                $code,
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        return [$tmpPath];
    }
}


text:
class ProfFakePosController < ApplicationController

  include GameLogic::ShowMap

  def create
    set_game_board

    cities_codes_names = params[ :cities_ids ]
    assert( @game_board.prof_asked_for_fake_cities?, "@game_board.aasm_state = #{@game_board.aasm_state}, should be prof_asked_for_fake_cities" )
    assert( @game_board.asked_fake_cities_count == cities_codes_names.count,
            "Bad city count#{@game_board.asked_fake_cities_count} != #{cities_codes_names.count}" )

    cities_codes_names.each.with_index(1) do |city_code_name, idx|
      update_last_fake_position_code_name(idx, city_code_name)
    end

    cities_codes_names << @prof.current_location_code_name.to_s
    cities_codes_names.uniq!

    # This case mean that somebody tried to send the prof location into the city_ids
    assert( @game_board.asked_fake_cities_count + 1 == cities_codes_names.count,
            "#{@game_board.asked_fake_cities_count + 1} != #{cities_codes_names.count}" )

    ActiveRecord::Base.transaction do

      prof_position_finder = GameCore::Ia::ProfPositionFinder.new
      prof_position_finder.load( @game_board )
      prof_position_finder.add_fake_pos( @game_board.turn, @prof,cities_codes_names )
      prof_position_finder.save( @game_board )

      @game_board.return_to_move_status!

      # The we need to finish the Investigators IA play
      # At the end of the professor move, investigators play
      @game_board.investigators_ia_play( @prof )
      @prof.save!
    end

    redirect_to g_game_board_play_url( @game_board )
  end

  private

  def update_last_fake_position_code_name( idx, city_code_name )
    if @prof.last_fake_position_1_code_name != city_code_name && @prof.last_fake_position_2_code_name != city_code_name
      save_location = "last_fake_position_#{idx}_code_name"
      @prof.update_attribute( save_location, city_code_name )
    end
  end

end


text:
package android.security;

import android.os.Environment;
import android.os.FileUtils;
import android.os.Process;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import libcore.io.IoUtils;

/**
 *@hide
 */
public class SystemKeyStore {

    private static final String SYSTEM_KEYSTORE_DIRECTORY = "misc/systemkeys";
    private static final String KEY_FILE_EXTENSION = ".sks";
    private static SystemKeyStore mInstance = new SystemKeyStore();

    private SystemKeyStore() { }

    public static SystemKeyStore getInstance() {
        return mInstance;
    }

    public static String toHexString(byte[] keyData) {
        if (keyData == null) {
            return null;
        }
        int keyLen = keyData.length;
        int expectedStringLen = keyData.length * 2;
        StringBuilder sb = new StringBuilder(expectedStringLen);
        for (int i = 0; i < keyData.length; i++) {
            String hexStr = Integer.toString(keyData[i] & 0x00FF, 16);
            if (hexStr.length() == 1) {
                hexStr = "0" + hexStr;
            }
            sb.append(hexStr);
        }
        return sb.toString();
    }

    public String generateNewKeyHexString(int numBits, String algName, String keyName)
            throws NoSuchAlgorithmException {
        return toHexString(generateNewKey(numBits, algName, keyName));
    }

    public byte[] generateNewKey(int numBits, String algName, String keyName)
            throws NoSuchAlgorithmException {

        // Check if key with similar name exists. If so, return null.
        File keyFile = getKeyFile(keyName);
        if (keyFile.exists()) {
            throw new IllegalArgumentException();
        }

        KeyGenerator skg = KeyGenerator.getInstance(algName);
        SecureRandom srng = SecureRandom.getInstance("SHA1PRNG");
        skg.init(numBits, srng);

        SecretKey sk = skg.generateKey();
        byte[] retKey = sk.getEncoded();

        try {
            // Store the key
            if (!keyFile.createNewFile()) {
                throw new IllegalArgumentException();
            }

            FileOutputStream fos = new FileOutputStream(keyFile);
            fos.write(retKey);
            fos.flush();
            FileUtils.sync(fos);
            fos.close();
            FileUtils.setPermissions(keyFile.getName(), (FileUtils.S_IRUSR | FileUtils.S_IWUSR),
                -1, -1);
        } catch (IOException ioe) {
            return null;
        }
        return retKey;
    }

    private File getKeyFile(String keyName) {
        File sysKeystoreDir = new File(Environment.getDataDirectory(),
                SYSTEM_KEYSTORE_DIRECTORY);
        File keyFile = new File(sysKeystoreDir, keyName + KEY_FILE_EXTENSION);
        return keyFile;
    }

    public String retrieveKeyHexString(String keyName) throws IOException {
        return toHexString(retrieveKey(keyName));
    }

    public byte[] retrieveKey(String keyName) throws IOException {
        File keyFile = getKeyFile(keyName);
        if (!keyFile.exists()) {
            return null;
        }
        return IoUtils.readFileAsByteArray(keyFile.toString());
    }

    public void deleteKey(String keyName) {

        // Get the file first.
        File keyFile = getKeyFile(keyName);
        if (!keyFile.exists()) {
            throw new IllegalArgumentException();
        }

        keyFile.delete();
    }
}


text:
using System.ComponentModel.DataAnnotations;

namespace Moonlit.Mvc.Sample.Models
{
    public class SignInModel
    {
        [Required]
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


text:
/**
 * @generated SignedSource<<fe2900274996215e7720d9d0f9b9c4ce>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { ConcreteRequest, Query } from 'relay-runtime';
import { FragmentRefs } from "relay-runtime";
export type UserRegistrationAuctions_Test_Query$variables = {};
export type UserRegistrationAuctions_Test_Query$data = {
  readonly me: {
    readonly " $fragmentSpreads": FragmentRefs<"UserRegistrationAuctions_me">;
  } | null;
};
export type UserRegistrationAuctions_Test_Query = {
  response: UserRegistrationAuctions_Test_Query$data;
  variables: UserRegistrationAuctions_Test_Query$variables;
};

const node: ConcreteRequest = (function(){
var v0 = {
  "alias": null,
  "args": null,
  "kind": "ScalarField",
  "name": "id",
  "storageKey": null
},
v1 = {
  "enumValues": null,
  "nullable": false,
  "plural": false,
  "type": "ID"
},
v2 = {
  "enumValues": null,
  "nullable": true,
  "plural": false,
  "type": "Boolean"
},
v3 = {
  "enumValues": null,
  "nullable": true,
  "plural": false,
  "type": "String"
};
return {
  "fragment": {
    "argumentDefinitions": [],
    "kind": "Fragment",
    "metadata": null,
    "name": "UserRegistrationAuctions_Test_Query",
    "selections": [
      {
        "alias": null,
        "args": null,
        "concreteType": "Me",
        "kind": "LinkedField",
        "name": "me",
        "plural": false,
        "selections": [
          {
            "args": null,
            "kind": "FragmentSpread",
            "name": "UserRegistrationAuctions_me"
          }
        ],
        "storageKey": null
      }
    ],
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": [],
    "kind": "Operation",
    "name": "UserRegistrationAuctions_Test_Query",
    "selections": [
      {
        "alias": null,
        "args": null,
        "concreteType": "Me",
        "kind": "LinkedField",
        "name": "me",
        "plural": false,
        "selections": [
          {
            "alias": null,
            "args": [
              {
                "kind": "Literal",
                "name": "first",
                "value": 10
              },
              {
                "kind": "Literal",
                "name": "isAuction",
                "value": true
              },
              {
                "kind": "Literal",
                "name": "published",
                "value": true
              },
              {
                "kind": "Literal",
                "name": "registered",
                "value": false
              },
              {
                "kind": "Literal",
                "name": "sort",
                "value": "CREATED_AT_DESC"
              }
            ],
            "concreteType": "SaleRegistrationConnection",
            "kind": "LinkedField",
            "name": "saleRegistrationsConnection",
            "plural": false,
            "selections": [
              {
                "alias": null,
                "args": null,
                "concreteType": "SaleRegistrationEdge",
                "kind": "LinkedField",
                "name": "edges",
                "plural": true,
                "selections": [
                  {
                    "alias": null,
                    "args": null,
                    "concreteType": "SaleRegistration",
                    "kind": "LinkedField",
                    "name": "node",
                    "plural": false,
                    "selections": [
                      {
                        "alias": null,
                        "args": null,
                        "kind": "ScalarField",
                        "name": "isRegistered",
                        "storageKey": null
                      },
                      {
                        "alias": null,
                        "args": null,
                        "concreteType": "Sale",
                        "kind": "LinkedField",
                        "name": "sale",
                        "plural": false,
                        "selections": [
                          (v0/*: any*/),
                          {
                            "alias": null,
                            "args": null,
                            "kind": "ScalarField",
                            "name": "name",
                            "storageKey": null
                          },
                          {
                            "alias": null,
                            "args": null,
                            "kind": "ScalarField",
                            "name": "href",
                            "storageKey": null
                          },
                          {
                            "alias": null,
                            "args": [
                              {
                                "kind": "Literal",
                                "name": "format",
                                "value": "MMMM D, h:mmA"
                              }
                            ],
                            "kind": "ScalarField",
                            "name": "startAt",
                            "storageKey": "startAt(format:\"MMMM D, h:mmA\")"
                          },
                          {
                            "alias": null,
                            "args": null,
                            "kind": "ScalarField",
                            "name": "isClosed",
                            "storageKey": null
                          },
                          {
                            "alias": null,
                            "args": null,
                            "kind": "ScalarField",
                            "name": "isRegistrationClosed",
                            "storageKey": null
                          }
                        ],
                        "storageKey": null
                      },
                      (v0/*: any*/)
                    ],
                    "storageKey": null
                  }
                ],
                "storageKey": null
              }
            ],
            "storageKey": "saleRegistrationsConnection(first:10,isAuction:true,published:true,registered:false,sort:\"CREATED_AT_DESC\")"
          },
          (v0/*: any*/)
        ],
        "storageKey": null
      }
    ]
  },
  "params": {
    "cacheID": "3415c0e9c92ccf9b5cc91b4557e778c8",
    "id": null,
    "metadata": {
      "relayTestingSelectionTypeInfo": {
        "me": {
          "enumValues": null,
          "nullable": true,
          "plural": false,
          "type": "Me"
        },
        "me.id": (v1/*: any*/),
        "me.saleRegistrationsConnection": {
          "enumValues": null,
          "nullable": true,
          "plural": false,
          "type": "SaleRegistrationConnection"
        },
        "me.saleRegistrationsConnection.edges": {
          "enumValues": null,
          "nullable": true,
          "plural": true,
          "type": "SaleRegistrationEdge"
        },
        "me.saleRegistrationsConnection.edges.node": {
          "enumValues": null,
          "nullable": true,
          "plural": false,
          "type": "SaleRegistration"
        },
        "me.saleRegistrationsConnection.edges.node.id": (v1/*: any*/),
        "me.saleRegistrationsConnection.edges.node.isRegistered": (v2/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale": {
          "enumValues": null,
          "nullable": true,
          "plural": false,
          "type": "Sale"
        },
        "me.saleRegistrationsConnection.edges.node.sale.href": (v3/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale.id": (v1/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale.isClosed": (v2/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale.isRegistrationClosed": (v2/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale.name": (v3/*: any*/),
        "me.saleRegistrationsConnection.edges.node.sale.startAt": (v3/*: any*/)
      }
    },
    "name": "UserRegistrationAuctions_Test_Query",
    "operationKind": "query",
    "text": "query UserRegistrationAuctions_Test_Query {\n  me {\n    ...UserRegistrationAuctions_me\n    id\n  }\n}\n\nfragment UserRegistrationAuctions_me on Me {\n  saleRegistrationsConnection(published: true, isAuction: true, sort: CREATED_AT_DESC, first: 10, registered: false) {\n    edges {\n      node {\n        isRegistered\n        sale {\n          id\n          name\n          href\n          startAt(format: \"MMMM D, h:mmA\")\n          isClosed\n          isRegistrationClosed\n        }\n        id\n      }\n    }\n  }\n}\n"
  }
};
})();

(node as any).hash = "73a75f1453c0aa9132600328932d6f7b";

export default node;


text:
package com.symagic.bean;

public class Photo {
	private String picName;
	private String description;

	public String getPicName() {
		return picName;
	}

	public void setPicName(String picName) {
		this.picName = picName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Photo(String picName, String description) {
		super();
		this.picName = picName;
		this.description = description;
	}

}


text:
namespace cert_trans {

template <class... LabelTypes>
class LabelledValues {
 public:
  LabelledValues(const std::string& name,
                 const typename NameType<LabelTypes>::name&... label_names);

  double Get(const LabelTypes&...) const;

  void Set(const LabelTypes&... labels, double value);

  void Increment(const LabelTypes&...);

  void IncrementBy(const LabelTypes&..., double value);

  std::map<std::vector<std::string>, Metric::TimestampedValue> CurrentValues()
      const;

 private:
  const std::string name_;
  const std::vector<std::string> label_names_;
  mutable std::mutex mutex_;
  std::map<std::tuple<LabelTypes...>,
           std::pair<std::chrono::system_clock::time_point, double>> values_;

  DISALLOW_COPY_AND_ASSIGN(LabelledValues);
};

namespace {

template <std::size_t>
struct i__ {};

template <class Tuple>
void label_values(const Tuple&, std::vector<std::string>*, i__<0>) {
}

template <class Tuple, size_t Pos>
void label_values(const Tuple& t, std::vector<std::string>* values, i__<Pos>) {
  std::ostringstream oss;
  oss << std::get<std::tuple_size<Tuple>::value - Pos>(t);
  CHECK_NOTNULL(values)->push_back(oss.str());
  label_values(t, values, i__<Pos - 1>());
}

template <class... Types>
std::vector<std::string> label_values(const std::tuple<Types...>& t) {
  std::vector<std::string> ret;
  label_values(t, &ret, i__<sizeof...(Types)>());
  return ret;
}

}  // namespace

template <class... LabelTypes>
LabelledValues<LabelTypes...>::LabelledValues(
    const std::string& name,
    const typename NameType<LabelTypes>::name&... label_names)
    : name_(name), label_names_{label_names...} {
}

template <class... LabelTypes>
double LabelledValues<LabelTypes...>::Get(const LabelTypes&... labels) const {
  std::lock_guard<std::mutex> lock(mutex_);
  const std::tuple<LabelTypes...> key(labels...);
  const auto it(values_.find(key));
  if (it == values_.end()) {
    return 0;
  }
  return it->second.second;
}

template <class... LabelTypes>
void LabelledValues<LabelTypes...>::Set(const LabelTypes&... labels,
                                        double value) {
  std::lock_guard<std::mutex> lock(mutex_);
  values_[std::tuple<LabelTypes...>(labels...)] =
      make_pair(std::chrono::system_clock::now(), value);
}

template <class... LabelTypes>
void LabelledValues<LabelTypes...>::Increment(const LabelTypes&... labels) {
  IncrementBy(labels..., 1);
}

template <class... LabelTypes>
void LabelledValues<LabelTypes...>::IncrementBy(const LabelTypes&... labels,
                                                double amount) {
  std::lock_guard<std::mutex> lock(mutex_);
  const std::tuple<LabelTypes...> key(labels...);
  const auto it(values_.find(key));
  if (it == values_.end()) {
    values_[key] = make_pair(std::chrono::system_clock::now(), amount);
    return;
  }
  values_[key] = make_pair(std::chrono::system_clock::now(),
                           values_[key].second + amount);
}

template <class... LabelTypes>
std::map<std::vector<std::string>, Metric::TimestampedValue>
LabelledValues<LabelTypes...>::CurrentValues() const {
  std::lock_guard<std::mutex> lock(mutex_);
  std::map<std::vector<std::string>, Metric::TimestampedValue> ret;

  for (const auto& v : values_) {
    ret[label_values(v.first)] = v.second;
  }
  return ret;
}

}  // namespace cert_trans

#endif  // CERT_TRANS_MONITORING_LABELLED_VALUES_H_


text:
from unittest import mock

from rafter.models import LogEntry

class Log(list):
    commit_index = -1
    cmp = mock.Mock(return_value=True)

    def entry(self, term, command, args, kwargs):
        self.append(LogEntry(dict(index=len(self), term=term, args=args, kwargs=kwargs)))
        return self[-1]

class Storage(dict):
    pass

async def foo(*args, **kwargs):
    return 'result'

class Service(mock.Mock):

    test = mock.MagicMock()
    test.apply = foo


text:
/*
 * Description:
 *     History: yang@haipo.me, 2017/03/21, create
 */

# ifndef _UT_LIST_H_
# define _UT_LIST_H_

typedef struct list_node {
    struct list_node *prev;
    struct list_node *next;
    void *value;
} list_node;

typedef struct list_iter {
    list_node *next;
    int direction;
} list_iter;

typedef struct list_type {
    void *(*dup)(void *value);
    void (*free)(void *value);
    int (*compare)(const void *value1, const void *value2);
} list_type;

typedef struct list_t {
    list_node *head;
    list_node *tail;
    list_type  type;
    unsigned long len;
} list_t;

# define list_len(l)        ((l)->len)
# define list_head(l)       ((l)->head)
# define list_tail(l)       ((l)->tail)
# define list_prev_node(n)  ((n)->prev)
# define list_next_node(n)  ((n)->next)
# define list_node_value(n) ((n)->value)

list_t *list_create(list_type *type);
list_t *list_add_node_head(list_t *list, void *value);
list_t *list_add_node_tail(list_t *list, void *value);
list_t *list_insert_node(list_t *list, list_node *pos, void *value, int before);
void list_del(list_t *list, list_node *node);
void list_clear(list_t *list);
void list_rotate(list_t *list);
void list_release(list_t *list);

# define LIST_START_HEAD 0
# define LIST_START_TAIL 1

list_iter *list_get_iterator(list_t *list, int direction);
list_node *list_next(list_iter *iter);
void list_rewind_head(list_t *list, list_iter *iter);
void list_rewind_tail(list_t *list, list_iter *iter);
void list_release_iterator(list_iter *iter);

list_t *list_dup(list_t *orig);
list_node *list_find(list_t *list, void *value);
list_node *list_index(list_t *list, long index);

# endif


text:
<?xml version="1.0" encoding="utf-8"?>
<!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" />
    <meta http-equiv="Content-Style-Type" content="text/css" />

    <title>caNanoLab_Glossary-1076867.html</title>
    <link rel="StyleSheet" href="../css/caNanoLab_Glossary.css" type="text/css" media="all" />
    <link rel="StyleSheet" href="../css/webworks.css" type="text/css" media="all" />

  <body style="background-color: #FFFFCC; cursor: pointer; cursor: hand; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-left: 6px; padding-right: 6px; padding-top: 6px; width: 250px;" onLoad="WWHUpdate();" onUnload="WWHUnload();" onKeyDown="WWHHandleKeyDown((document.all||document.getElementById||document.layers)?event:null);" onKeyPress="WWHHandleKeyPress((document.all||document.getElementById||document.layers)?event:null);" onKeyUp="WWHHandleKeyUp((document.all||document.getElementById||document.layers)?event:null);">

An oxygen species that carries an unpaired electron (e.g., the hydroxyl radical and the superoxide anion). These radicals are very powerful oxidizing agents and cause structural damage to proteins and nucleic acids.


text:
import os, sys; sys.path.insert(0, os.path.join("..", ".."))

from pattern.web import Flickr, extension
from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order.
from pattern.web import SMALL, MEDIUM, LARGE           # Image size.

# This example downloads an image from Flickr (http://flickr.com).
# Acquiring the image data takes three Flickr queries:
# - the first query with Flickr.search() retrieves a list of results,
# - the second query is executed behind the scenes in the FlickResult.url property,
# - the third query downloads the actual image data using this URL.
# It is a good idea to cache results from Flickr locally,
# which is what the cached=True parameter does.

# You should obtain your own license key at:
# http://www.flickr.com/services/api/
# Otherwise you will be sharing the default key with all users of this module.
engine = Flickr(license=None)

q = "duracell bunny"
results = engine.search(q, size=MEDIUM, sort=RELEVANCY, cached=True)
for img in results:
    #print img.url # Retrieving the actual image URL executes an additional query.
    print img.description
    print img.author
    print

# Download and save the image:
img = results[0]
data = img.download()
path = q.replace(" ","_") + extension(img.url)
f = open(path, "wb")
f.write(data)
f.close()
print "Download:", img.url
print "Saved as:", path


text:
@protocol GalleryViewDelegate;

@interface GalleryView : UIView <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet id <GalleryViewDelegate>    delegate;

@property (nonatomic, strong, readonly) UIScrollView    *scrollView;
@property (assign, nonatomic, readonly) NSInteger       currentPage;

@property (assign, nonatomic) CGFloat maximumZoomScale;//默认为1
@property (assign, nonatomic) CGFloat minimumZoomScale;//默认为3

@property (strong, nonatomic) NSArray *images;

//- (void)setImages:(NSArray *)images withContentView:(UIView *)aview;

@end

@protocol GalleryViewDelegate <NSObject>

@optional

//滑动时,切换到某一页时调用
- (void)galleryView:(GalleryView *)galleryView didShowPageAtIndex:(NSInteger)pageIndex;

//点击某一页时调用
- (void)galleryView:(GalleryView *)galleryView didSelectPageAtIndex:(NSInteger)pageIndex;

@end


text:
Zest.Telephony.Views.ConversationView = Backbone.View.extend({
  className: 'conversation-wrapper',

  events: {
    'click button.initiate-conversation' : 'createConversation',
    'click button.cancel-transfer': 'cancelTransfer',
    'click button.initiate-hold': 'hold',
    'click button.resume': 'resume',
    'click button.show-agents': 'openTransferView'
  },

  template: JST["templates/telephony/conversation_view"],

  initialize: function() {
    this.setupNewConversation();

    $(document)
      .bind("transferInitiated", $.proxy(this.cancelTransfer, this))
      .bind('callFailed', $.proxy(this.displayCallFailedMessage, this))
      .bind('holdResumeFail', $.proxy(this.displayHoldResumeFailedMessage, this))
      .bind('transferFailed', $.proxy(this.displayTransferFailedMessage, this))
      .bind("telephony:InitializeWidget", $.proxy(this.onInitializeWidget, this))
      .bind("telephony:ClickToCall", $.proxy(this.onClickToCall, this))
      .bind("telephony:Connect", $.proxy(this.onConnect, this))
      .bind("telephony:Start", $.proxy(this.onStart, this))
      .bind("telephony:Busy telephony:NoAnswer telephony:CallFail telephony:Terminate",
            $.proxy(this.onCallEnded, this))
      .bind("telephony:InitiateOneStepTransfer", $.proxy(this.onInitiateOneStepTransfer, this))
      .bind("telephony:CompleteOneStepTransfer", $.proxy(this.onCompleteOneStepTransfer, this))
      .bind("telephony:FailOneStepTransfer", $.proxy(this.onFailOneStepTransfer, this))
      .bind("telephony:InitiateTwoStepTransfer", $.proxy(this.onInitiateTwoStepTransfer, this))
      .bind("telephony:CompleteTwoStepTransfer", $.proxy(this.onCompleteTwoStepTransfer, this))
      .bind("telephony:CustomerLeftTwoStepTransfer", $.proxy(this.onCustomerLeftTwoStepTransfer, this))
      .bind("telephony:LeaveTwoStepTransfer", $.proxy(this.onLeaveTwoStepTransfer, this))
      .bind("telephony:CompleteHold", $.proxy(this.onCompleteHold, this))
      .bind("telephony:CompleteResume", $.proxy(this.onCompleteResume, this))
      .bind("telephony:FailTwoStepTransfer", $.proxy(this.onFailTwoStepTransfer, this));
  },

  hold: function() {
    this.conversation.hold();
  },

  resume: function() {
    this.conversation.resume();
  },

  displayCallFailedMessage: function(event, data) {
    this.friendlyMessage = data;
    this.conversation.set({state: "not_initiated"});
  },

  displayTransferFailedMessage: function(event, data) {
    this.friendlyMessage = data;
    this.conversation.set({state: "in_progress"});
  },

  displayHoldResumeFailedMessage: function(event, data) {
    this.friendlyMessage = data.error;

    if (this.conversation.get('state') === data.newState) {
      this.conversation.set({state: data.oldState});
    } else {
      this.render();
    }
  },

  onInitializeWidget: function() {
    this.friendlyMessage = "";
    this.conversation.set({state: "not_initiated"});
  },

  disableCallControl: function(opts) {
    this.conversation.set({callingDisabled: opts.callingDisabled});
    this.render();
  },

  setupNewConversation: function() {
    this.conversation = new Zest.Telephony.Models.Conversation({
      loanId: this.options.loanId,
      from: this.options.agentNumber,
      fromId: this.options.fromId
    });
    this.conversation
      .bind("change:state", $.proxy(this.render, this));
  },

  showCancelTransfer: function() {
    this.conversation.set({isCancelable: true});
  },

  cancelTransfer: function() {
    $(this.el).animate({height: '50px'});

    this.conversation.set({isCancelable: false});
    this.transferView = null;
    this.render();
  },

  createConversation: function(event) {
    this.setupNewConversation();

    event.preventDefault();
    var number = this.$('input[name=number]').val();
    this.conversation.set({
      to: number,
      state: "not_initiated"
    });
    if (this.conversation.isValid()) {
      this.friendlyMessage = "";
      this.conversation.create();
    } else {
      this.friendlyMessage = this.conversation.errorMessage;
      this.render();
    }
  },

  onClickToCall: function(event, data) {
    this.conversation.set({
      to: data.to,
      toId: data.to_id,
      toType: data.to_type
    });
    this.friendlyMessage = data.callee_name || '';
    this.render();
  },

  onConnect: function (event, data) {
    this.friendlyMessage = 'Ringing';
    this.setConversationData(data);
    this.render();
  },

  setConversationData: function(data) {
    this.conversation.set({
      to: data.number,
      state: data.conversation_state,
      id: data.conversation_id,
      owner: data.owner
    });
  },

  openTransferView: function(event) {
    event.preventDefault();
    this.showAgents();
  },

  showAgents: function() {
    this.showCancelTransfer();
    $(this.el).animate({height: '100px'});

    var $transferWrapper = this.$('.transfer-wrapper');

    var conversationId = this.conversation.get("id");

    if(this.transferView) {
      this.transferView.el = $transferWrapper;
      this.transferView.conversationId = conversationId;
      this.transferView.rebindEvents();
    } else {
      this.transferView = new Zest.Telephony.Views.TransferView({
        el: $transferWrapper,
        conversationId: conversationId
      });
    }
    this.transferView.render();
  },

  onStart: function(event, data) {
    this.friendlyMessage = 'Connected';
    this.setConversationData(data);
    this.render();
  },

  onCallEnded: function(event, data) {
    this.friendlyMessage = 'Call Ended';
    this.conversation.set({
      to: '',
      state: 'terminated',
      id: data.conversation_id,
      owner: data.owner,
      isCancelable: false
    });
    this.render();
    $(this.el).animate({height: '50px'});
    this.$('.friendly-message').animate({ opacity: 0 },
                                        this.friendlyMessageFadeOutTime || 5000);
  },

  onInitiateOneStepTransfer: function(event, data) {
    if (data.transferrer) {
      return;
    }
    this.friendlyMessage = '1-step transfer from ' + data.agent_type + " - " +
      data.agent_name + ' x' + data.agent_ext;

    this.setConversationData(data);
    this.render();
  },

  onCompleteOneStepTransfer: function(event, data) {
    this.friendlyMessage = 'Connected';
    this.setConversationData(data);
    this.render();
  },

  onFailOneStepTransfer: function(event, data) {
    if (data.transferrer) {
      this.conversation.set({
        state: 'terminated'
      });
      return;
    }
    this.friendlyMessage = 'Missed 1-step transfer from ' + data.agent_type + " - " +
      data.agent_name + ' x' + data.agent_ext;

    this.conversation.set({
      id: data.conversation_id,
      state: 'terminated',
      to: data.number,
      owner: data.owner
    });
    this.render();
  },

  onInitiateTwoStepTransfer: function(event, data) {
    if (data.transferrer) {
      this.friendlyMessage = 'Ringing ' + data.agent_type + " - " +
        data.agent_name + ' x' + data.agent_ext;
    } else {
      this.friendlyMessage = '2-step transfer from ' + data.agent_type + " - " +
        data.agent_name + ' x' + data.agent_ext;
    }

    this.conversation.set({
      disabledTransfer: true,
      state: data.conversation_state,
      to: data.number,
      owner: data.owner
    });
    this.render();
  },

  onFailTwoStepTransfer: function(event, data) {
    if (data.transferrer) {
      this.friendlyMessage = 'No Answer - ' + data.agent_name + " x" +
        data.agent_ext;
      this.nextFriendlyMessage = "Connected";

      this.setConversationData(data);
      this.render();
      this.$('.friendly-message').animate({ opacity: 0 },
          { duration: this.friendlyMessageFadeOutTime || 5000,
            complete: $.proxy(this.afterFriendlyMessageDecay, this)
          });
    } else {
      this.friendlyMessage = 'Missed 2-step transfer from ' + data.agent_type + " - " +
        data.agent_name + ' x' + data.agent_ext;

      this.conversation.set({
        to: data.number,
        state: 'terminated',
        id: data.conversation_id,
        owner: data.owner
      });
      this.render();
    }
  },

  afterFriendlyMessageDecay: function() {
    if (this.nextFriendlyMessage) {
      this.friendlyMessage = this.nextFriendlyMessage;
      this.nextFriendlyMessage = null;
      this.render();
    }
  },

  onCompleteTwoStepTransfer: function(event, data) {
    this.friendlyMessage = 'Connected to ' + data.agent_type + " - " +
      data.agent_name + ' x' + data.agent_ext;
    this.setConversationData(data);
    this.render();
  },

  onCustomerLeftTwoStepTransfer: function(event, data) {
    this.friendlyMessage = 'Connected to ' + data.agent_type + " - " +
      data.agent_name + ' x' + data.agent_ext;
    this.setConversationData(data);
    this.render();
  },

  onLeaveTwoStepTransfer: function(event, data) {
    this.friendlyMessage = 'Connected';
    this.setConversationData(data);
    this.render();
  },

  onCompleteHold: function(event, data) {
    this.setConversationData(data);
  },

  onCompleteResume: function(event, data) {
    this.setConversationData(data);
  },

  render: function () {
    var html = this.template({
      conversation: this.conversation,
      friendlyMessage: this.friendlyMessage
    });
    $(this.el).html(html);

    this.buttonsView = new Zest.Telephony.Views.ConversationButtonsView({
      conversation: this.conversation
    });
    this.$('form').append(this.buttonsView.render().el);
    if (this.conversation.get('isCancelable')) {
      this.showAgents();
    }
    return this;
  }
});


text:
'use strict';

//Setting up route
angular.module('companies').config(['$stateProvider',
	function($stateProvider) {
		// Companies state routing
		$stateProvider.
		state('listCompanies', {
			url: '/companies',
			templateUrl: 'modules/companies/views/list.html'
		}).
		state('createCompany', {
			url: '/companies/create',
			templateUrl: 'modules/companies/views/create.html'
		}).
		state('viewCompany', {
			url: '/companies/:companyId',
			templateUrl: 'modules/companies/views/view.html'
		}).
		state('editCompany', {
			url: '/companies/:companyId/edit',
			templateUrl: 'modules/companies/views/edit.html'
		});
	}
]);


text:
ip=$1
domain=$2

if [ -z $domain ]; then
    echo -en "Enter the domain for your new site (default: wordpress.local): "
    read domain
    if [ -z $domain ]; then
        domain=wordpress.local
    fi
fi

if [ -z $ip ]; then
    echo -en "Enter IP for the Vagrant machine to use (default: 192.168.30.11): "
    read ip
    if [ -z $ip ]; then
        ip=192.168.30.11
    fi
fi

echo "Building Vagrantfile"
sed -i '' -e "s/\[IP\]/$ip/g" Vagrantfile

echo "Building Virtual Host config file"
sed -i '' -e "s/\[DOMAIN\]/$domain/g" provision/wordpress

echo "Creating .env file"
echo -e "
DB_NAME=wordpress
DB_USER=root
DB_PASSWORD=root
DB_HOST=localhost

WP_ENV=development
WP_HOME=http://$domain
WP_SITEURL=http://$domain/wp
" > .env

cat <<EOF

========================
   Project configured
========================
IP: $ip
Domain: $domain
Site URL: http://$domain
Admin URL: http://$domain/wp/wp-admin

You can now run "vagrant up" command.

Please remember to update your /etc/hosts file with the following entry:
$ip $domain

EOF

rm $0 # self-removal


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="EntryPointsManager">
    <entry_points version="2.0" />
  </component>
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Abstraction issues</id>
          </State>
          <State>
            <id>Android</id>
          </State>
          <State>
            <id>Android Lint</id>
          </State>
          <State>
            <id>Assignment issues</id>
          </State>
          <State>
            <id>Assignment issuesGroovy</id>
          </State>
          <State>
            <id>Bitwise operation issues</id>
          </State>
          <State>
            <id>Class metrics</id>
          </State>
          <State>
            <id>Class structure</id>
          </State>
          <State>
            <id>Code maturity issues</id>
          </State>
          <State>
            <id>Code style issues</id>
          </State>
          <State>
            <id>Control FlowGroovy</id>
          </State>
          <State>
            <id>Control flow issues</id>
          </State>
          <State>
            <id>Data flow issues</id>
          </State>
          <State>
            <id>Declaration redundancy</id>
          </State>
          <State>
            <id>Dependency issues</id>
          </State>
          <State>
            <id>Encapsulation issues</id>
          </State>
          <State>
            <id>Error handling</id>
          </State>
          <State>
            <id>Error handlingGroovy</id>
          </State>
          <State>
            <id>GPath inspectionsGroovy</id>
          </State>
          <State>
            <id>General</id>
          </State>
          <State>
            <id>Google Cloud Endpoints</id>
          </State>
          <State>
            <id>Groovy</id>
          </State>
          <State>
            <id>Imports</id>
          </State>
          <State>
            <id>Inheritance issues</id>
          </State>
          <State>
            <id>Initialization issues</id>
          </State>
          <State>
            <id>Internationalization issues</id>
          </State>
          <State>
            <id>J2ME issues</id>
          </State>
          <State>
            <id>JUnit issues</id>
          </State>
          <State>
            <id>Java language level issues</id>
          </State>
          <State>
            <id>Java language level migration aids</id>
          </State>
          <State>
            <id>Javadoc issues</id>
          </State>
          <State>
            <id>Logging issues</id>
          </State>
          <State>
            <id>Maven</id>
          </State>
          <State>
            <id>Method MetricsGroovy</id>
          </State>
          <State>
            <id>Method metrics</id>
          </State>
          <State>
            <id>Naming ConventionsGroovy</id>
          </State>
          <State>
            <id>Naming conventions</id>
          </State>
          <State>
            <id>Numeric issues</id>
          </State>
          <State>
            <id>Packaging issues</id>
          </State>
          <State>
            <id>Pattern Validation</id>
          </State>
          <State>
            <id>Performance issues</id>
          </State>
          <State>
            <id>Portability issues</id>
          </State>
          <State>
            <id>Potentially confusing code constructsGroovy</id>
          </State>
          <State>
            <id>Probable bugs</id>
          </State>
          <State>
            <id>Probable bugsGroovy</id>
          </State>
          <State>
            <id>Properties Files</id>
          </State>
          <State>
            <id>RELAX NG</id>
          </State>
          <State>
            <id>Security issues</id>
          </State>
          <State>
            <id>Serialization issues</id>
          </State>
          <State>
            <id>TestNG</id>
          </State>
          <State>
            <id>Threading issues</id>
          </State>
          <State>
            <id>Threading issuesGroovy</id>
          </State>
          <State>
            <id>Verbose or redundant code constructs</id>
          </State>
          <State>
            <id>Visibility issues</id>
          </State>
          <State>
            <id>XML</id>
          </State>
        </expanded-state>
        <selected-state>
          <State>
            <id>Abstraction issues</id>
          </State>
        </selected-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/build/classes" />
  </component>
  <component name="masterDetails">
    <states>
      <state key="ProjectJDKs.UI">
        <settings>
          <last-edited>Android API 14 Platform</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="ScopeChooserConfigurable.UI">
        <settings>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
    </states>
  </component>
</project>


text:
<?php
//==============================================================
//  CodeBits Platform
//  Open Source PHP Framework for Applications and Websites
//  by Ilya Rastorguev
//==============================================================
//  Файл:           index.php
//  Назначение:     Главный исполнительный файл Frontend
//  Разработчик:    InterWave
//  Версия:         1.0
//==============================================================
define("WRAPPER", true); // Задаем просмотр через враппер
define("FRONTEND", __DIR__.'/frontend'); // Frontend Folder
define("GLOBALROOT", __DIR__); // Самый корень
include(__DIR__.'/api/index.php'); // Подключить ядро API
?>


text:
<left-side-bar-arabic></left-side-bar-arabic>

            التقارير (وكلاء المبيعات )

                                <button class="btn btn-box-tool refresh-btn" data-toggle="tooltip" title="Reload" ng-click="searchAgentByParamter(searchAgentName,searchAgentCompany,searchAgentNumber)"></button>
                                <button type="submit" class="btn btn-box-tool btn-sm" data-widget='collapse' data-toggle="tooltip" title="Collapse"></button>

تصفية حسب الشهر

                                Month
                                <select class="form-control" ng-model="filterMonth" ng-change="getMonth(filterMonth)">
                                    <option>-- Please Select --</option>
                                    <option value="1">January</option>
                                    <option value="2">February</option>
                                    <option value="3">March</option>
                                    <option value="4">April</option>
                                    <option value="5">May</option>
                                    <option value="6">June</option>
                                    <option value="7">July</option>
                                    <option value="8">August</option>
                                    <option value="9">September</option>
                                    <option value="10">October</option>
                                    <option value="11">November</option>
                                    <option value="12">December</option>
                                </select>

                                <input type="submit" class="btn btn-primary" style="width:100px" value="منقي" ng-click="filterByMonth()" />

                                <button class="btn"> طباعة</button>

وكلاء المبيعات

                                        Page
                                        <button id="prev" type="submit" title="Previous Page" class="paging-button"></button>
                                        <input type="text" class="form-control page-number" value="1" />
                                        <button id="next" type="submit" title="Next Page" class="paging-button"></button>
                                of 10 Pages
                                <select class="form-control psize">
                                    <option value="20">20</option>
                                    <option value="30" selected>30</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                    <option value="200">200</option>
                                </select>

                                        هوية شخصية
                                        اسم
                                         اللجنة الحالية
                                        اللجنة الحالية
                                        عنوان البريد الإلكتروني
                                        رقم الهاتف المحمول
                                        مجموع المحول
                                        توتلا الإحالات
                                        توتلا مسجل
                                        اكتب

                                        {{x.Id}}
                                        {{x.FirstName +" " +x.LastName}}
                                        {{x.CurrentCommission}}
                                        {{x.CompanyName}}
                                        {{x.EmailAddress}}
                                        {{x.ContactNumber}}
                                        {{x.TotalConverted}}
                                        {{x.TotalReferrals}}
                                        {{x.TotalRegistered}}
                                        {{x.Type}}


text:
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Zookeeper.Store (
  deleteRecursive
, BackendKey(..)
)where

import Control.Applicative ((<$>))

import Database.Persist
import qualified Database.Persist.Sql as Sql
import qualified Database.Zookeeper as Z
import Data.Monoid
import qualified Data.Text as T
import Database.Persist.Zookeeper.Config
import Database.Persist.Zookeeper.Internal
import Database.Persist.Zookeeper.ZooUtil
import Control.Monad
import Control.Monad.Reader
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A

import Web.PathPieces (PathPiece(..))
import Web.HttpApiData (ToHttpApiData (..), FromHttpApiData (..), parseUrlPieceMaybe, parseUrlPieceWithPrefix)

instance ToHttpApiData (BackendKey Z.Zookeeper) where
    toUrlPiece key = "z" <> unZooKey key

instance FromHttpApiData (BackendKey Z.Zookeeper) where
    parseUrlPiece input = ZooKey <$> parseUrlPieceWithPrefix "z" input

-- | ToPathPiece is used to convert a key to/from text
instance PathPiece (BackendKey Z.Zookeeper) where
  toPathPiece   = toUrlPiece
  fromPathPiece = parseUrlPieceMaybe

instance Sql.PersistFieldSql (BackendKey Z.Zookeeper) where
    sqlType _ = Sql.SqlOther "doesn't make much sense for Zookeeper"

instance A.ToJSON (BackendKey Z.Zookeeper) where
    toJSON (ZooKey key) = A.toJSON $ "z" <> key

instance A.FromJSON (BackendKey Z.Zookeeper) where
    parseJSON v = A.modifyFailure ("Persistent: error loading Zookeeper conf: " ++) $
      flip (A.withText "ZooKey") v $ \t ->
        case T.uncons t of
          Just ('z', prefixed) -> return $ ZooKey prefixed
          _ -> (fail "Invalid json for zookey")

deleteRecursive :: (Monad m, MonadIO m) => String -> Action m ()
deleteRecursive dir = execZookeeper $ \zk -> zDeleteRecursive zk dir

instance PersistStore Z.Zookeeper where
    newtype BackendKey Z.Zookeeper = ZooKey { unZooKey :: T.Text }
        deriving (Show, Read, Eq, Ord, PersistField)

    insert val = do
      mUniqVal <- val2uniqkey val
      case mUniqVal of
        Just uniqVal -> do
          let key = (uniqkey2key uniqVal)
          execZookeeper $ \zk -> do
            let dir = entity2path val
            r <- zCreate zk dir (keyToTxt key) (Just (entity2bin val)) []
            case r of
              Right _ -> return $ Right $ key
--              Left Z.NodeExistsError -> return $ Right $ Nothing
              Left v -> return $ Left v
        Nothing -> do
          let dir = entity2path val
          str <- execZookeeper $ \zk -> do
            zCreate zk dir "" (Just (entity2bin val)) [Z.Sequence]
          return $ txtToKey str

    insertKey key val = do
      _ <- execZookeeper $ \zk -> do
        let dir = entity2path val
        zCreate zk dir (keyToTxt key) (Just (entity2bin val)) []
      return ()

    repsert key val = do
      _ <- execZookeeper $ \zk -> do
        let dir = entity2path val
        zRepSert zk dir (keyToTxt key) (Just (entity2bin val))
      return ()

    replace key val = do
      execZookeeper $ \zk -> do
        let dir = entity2path val
        _ <- zReplace zk dir (keyToTxt key) (Just (entity2bin val))
        return $ Right ()
      return ()

    delete key = do
      execZookeeper $ \zk -> do
        let dir = key2path key
        _ <- zDelete zk dir (keyToTxt key) Nothing
        return $ Right ()
      return ()

    get key = do
      r <- execZookeeper $ \zk -> do
        let dir = key2path key
        val <- zGet zk dir (keyToTxt key)
        return $ Right val
      case r of
        (Left Z.NoNodeError) ->
          return Nothing
        (Left v) ->
          fail $ show v
        (Right (Just str,_sta)) -> do
          return (bin2entity str)
        (Right (Nothing,_stat)) -> do
          fail $ "data is nothing"

    update key valList = do
      va <- get key
      case va of
        Nothing -> return ()
        Just v ->
          case updateEntity v valList of
            Right v' ->
              replace key v'
            Left v' -> error $ show v'


text:
package libcore.java.nio.channels;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import junit.framework.TestCase;
import tests.support.Support_PortManager;

/*
 * test for ServerSocketChannel
 */
public class OldServerSocketChannelTest extends TestCase {

    private static final int TIME_UNIT = 200;

    private InetSocketAddress localAddr1;

    private ServerSocketChannel serverChannel;

    private SocketChannel clientChannel;

    protected void setUp() throws Exception {
        super.setUp();
        this.localAddr1 = new InetSocketAddress(
                "127.0.0.1", Support_PortManager
                        .getNextPort());
        this.serverChannel = ServerSocketChannel.open();
        this.clientChannel = SocketChannel.open();
    }

    protected void tearDown() throws Exception {
        if (null != this.serverChannel) {
            try {
                this.serverChannel.close();
            } catch (Exception e) {
                //ignore
            }

        }
        if (null != this.clientChannel) {
            try {
                this.clientChannel.close();
            } catch (Exception e) {
                //ignore
            }
        }
        super.tearDown();
    }

    // -------------------------------------------------------------------
    // Test for methods in abstract class.
    // -------------------------------------------------------------------
    public void testConstructor() throws IOException {
        ServerSocketChannel channel =
                SelectorProvider.provider().openServerSocketChannel();
        assertNotNull(channel);
        assertSame(SelectorProvider.provider(),channel.provider());
    }

    public void testIsOpen() throws Exception {
        assertTrue(this.serverChannel.isOpen());
        this.serverChannel.close();
        assertFalse(this.serverChannel.isOpen());
    }

    public void test_accept_Block_NoConnect_interrupt() throws IOException {
        assertTrue(this.serverChannel.isBlocking());
        ServerSocket gotSocket = this.serverChannel.socket();
        gotSocket.bind(localAddr1);

        class MyThread extends Thread {
            public String errMsg = null;
            public void run() {
                try {
                    serverChannel.accept();
                    errMsg = "should throw ClosedByInterruptException";
                } catch (ClosedByInterruptException e) {
                    // expected
                } catch (Exception e) {
                    errMsg = "caught wrong Exception: " + e.getClass() + ": " +
                            e.getMessage();
                }
            }
        }
        MyThread thread = new MyThread();
        thread.start();
        try {
            Thread.currentThread().sleep(TIME_UNIT);
            thread.interrupt();
        } catch (InterruptedException e) {
            fail("Should not throw a InterruptedException");
        }
        if (thread.errMsg != null) {
            fail(thread.errMsg);
        }
    }
}


text:
class Watchman < Formula
  desc "Watch files and take action when they change"
  homepage "https://github.com/facebook/watchman"
  revision 2
  head "https://github.com/facebook/watchman.git"

  stable do
    url "https://github.com/facebook/watchman/archive/v4.9.0.tar.gz"
    sha256 "1f6402dc70b1d056fffc3748f2fdcecff730d8843bb6936de395b3443ce05322"

    # Upstream commit from 1 Sep 2017: "Have bin scripts use iter() method for python3"
    patch do
      url "https://github.com/facebook/watchman/commit/17958f7d.diff?full_index=1"
      sha256 "edad4971fceed2aecfa2b9c3e8e22c455bfa073732a3a0c77b030e506ee860af"
    end
  end

  bottle do
    sha256 "fd932d78fec199bbd71e7f192eb16deb728d0d7aeb26127fd0827221de2d92cb" => :mojave
    sha256 "83e3c11bdb57ba39b51c4d9e17fb38638f541a17343be51106f7409df17c7bf3" => :high_sierra
    sha256 "a6ae3a7240b6427a44a032fa2d1d23743bdcc4a8cf3ee80276eac895028b470b" => :sierra
  end

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "libtool" => :build
  depends_on "pkg-config" => :build
  depends_on :macos => :yosemite # older versions don't support fstatat(2)
  depends_on "openssl"
  depends_on "pcre"
  depends_on "python"

  def install
    system "./autogen.sh"
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--with-pcre",
                          # Do homebrew specific Python installation below
                          "--without-python",
                          "--enable-statedir=#{var}/run/watchman"
    system "make"
    system "make", "install"

    # Homebrew specific python application installation
    xy = Language::Python.major_minor_version "python3"
    ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{xy}/site-packages"
    cd "python" do
      system "python3", *Language::Python.setup_install_args(libexec)
    end
    bin.install Dir[libexec/"bin/*"]
    bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
  end

  def post_install
    (var/"run/watchman").mkpath
    chmod 042777, var/"run/watchman"
    # Older versions would use socket activation in the launchd.plist, and since
    # the homebrew paths are versioned, this meant that launchd would continue
    # to reference the old version of the binary after upgrading.
    # https://github.com/facebook/watchman/issues/358
    # To help swing folks from an older version to newer versions, force unloading
    # the plist here.  This is needed even if someone wanted to add brew services
    # support; while there are still folks with watchman <4.8 this is still an
    # upgrade concern.
    home = ENV["HOME"]
    system "launchctl", "unload",
           "-F", "#{home}/Library/LaunchAgents/com.github.facebook.watchman.plist"
  end

  test do
    assert_equal /(\d+\.\d+\.\d+)/.match(version)[0], shell_output("#{bin}/watchman -v").chomp
  end
end