text:
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
/* cairo - a vector graphics library with display and print output
 *
 * Copyright © 2005 Red Hat, Inc
 *
 * This library is free software; you can redistribute it and/or
 * modify it either under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * (the "LGPL") or, at your option, under the terms of the Mozilla
 * Public License Version 1.1 (the "MPL"). If you do not alter this
 * notice, a recipient may use your version of this file under either
 * the MPL or the LGPL.
 *
 * You should have received a copy of the LGPL along with this library
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 * You should have received a copy of the MPL along with this library
 * in the file COPYING-MPL-1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
 * the specific language governing rights and limitations.
 *
 * The Original Code is the cairo graphics library.
 *
 * The Initial Developer of the Original Code is Red Hat, Inc.
 *
 * Author(s):
 *	Kristian Høgsberg <krh@redhat.com>
 */

#include "cairoint.h"
#include "cairo-output-stream-private.h"

typedef struct _cairo_base85_stream {
    cairo_output_stream_t base;
    cairo_output_stream_t *output;
    unsigned char four_tuple[4];
    int pending;
} cairo_base85_stream_t;

static void
_expand_four_tuple_to_five (unsigned char four_tuple[4],
			    unsigned char five_tuple[5],
			    cairo_bool_t *all_zero)
{
    uint32_t value;
    int digit, i;

    value = four_tuple[0] << 24 | four_tuple[1] << 16 | four_tuple[2] << 8 | four_tuple[3];
    if (all_zero)
	*all_zero = TRUE;
    for (i = 0; i < 5; i++) {
	digit = value % 85;
	if (digit != 0 && all_zero)
	    *all_zero = FALSE;
	five_tuple[4-i] = digit + 33;
	value = value / 85;
    }
}

static cairo_status_t
_cairo_base85_stream_write (cairo_output_stream_t *base,
			    const unsigned char	  *data,
			    unsigned int	   length)
{
    cairo_base85_stream_t *stream = (cairo_base85_stream_t *) base;
    const unsigned char *ptr = data;
    unsigned char five_tuple[5];
    cairo_bool_t is_zero;

    while (length) {
	stream->four_tuple[stream->pending++] = *ptr++;
	length--;
	if (stream->pending == 4) {
	    _expand_four_tuple_to_five (stream->four_tuple, five_tuple, &is_zero);
	    if (is_zero)
		_cairo_output_stream_write (stream->output, "z", 1);
	    else
		_cairo_output_stream_write (stream->output, five_tuple, 5);
	    stream->pending = 0;
	}
    }

    return _cairo_output_stream_get_status (stream->output);
}

static cairo_status_t
_cairo_base85_stream_close (cairo_output_stream_t *base)
{
    cairo_base85_stream_t *stream = (cairo_base85_stream_t *) base;
    unsigned char five_tuple[5];

    if (stream->pending) {
	memset (stream->four_tuple + stream->pending, 0, 4 - stream->pending);
	_expand_four_tuple_to_five (stream->four_tuple, five_tuple, NULL);
	_cairo_output_stream_write (stream->output, five_tuple, stream->pending + 1);
    }

    /* Mark end of base85 data */
    _cairo_output_stream_printf (stream->output, "~>");

    return _cairo_output_stream_get_status (stream->output);
}

cairo_output_stream_t *
_cairo_base85_stream_create (cairo_output_stream_t *output)
{
    cairo_base85_stream_t *stream;

    if (output->status)
	return _cairo_output_stream_create_in_error (output->status);

    stream = malloc (sizeof (cairo_base85_stream_t));
    if (stream == NULL) {
	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
	return (cairo_output_stream_t *) &_cairo_output_stream_nil;
    }

    _cairo_output_stream_init (&stream->base,
			       _cairo_base85_stream_write,
			       _cairo_base85_stream_close);
    stream->output = output;
    stream->pending = 0;

    return &stream->base;
}


text:
<?php

namespace Oro\Bundle\SearchBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

use Oro\Bundle\SearchBundle\Provider\ResultStatisticsProvider;
use Oro\Bundle\SecurityBundle\Annotation\Acl;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;

class SearchController extends Controller
{
    /**
     * @Route("/advanced-search", name="oro_search_advanced")
     *
     * @Acl(
     *      id="oro_search",
     *      type="action",
     *      label="oro.search.module_name",
     *      group_name=""
     * )
     */
    public function ajaxAdvancedSearchAction()
    {
        return $this->getRequest()->isXmlHttpRequest()
            ? new JsonResponse(
                $this->get('oro_search.index')->advancedSearch(
                    $this->getRequest()->get('query')
                )->toSearchResultData()
            )
            : $this->forward('OroSearchBundle:Search:searchResults');
    }

    /**
     * Show search block
     *
     * @Route("/search-bar", name="oro_search_bar")
     * @Template("OroSearchBundle:Search:searchBar.html.twig")
     * @AclAncestor("oro_search")
     */
    public function searchBarAction()
    {
        return array(
            'entities'     => $this->get('oro_search.index')->getAllowedEntitiesListAliases(),
            'searchString' => $this->getRequest()->get('searchString'),
            'fromString'   => $this->getRequest()->get('fromString'),
        );
    }

    /**
     * Show search results
     *
     * @Route("/", name="oro_search_results")
     * @Template("OroSearchBundle:Search:searchResults.html.twig")
     *
     * @AclAncestor("oro_search")
     */
    public function searchResultsAction(Request $request)
    {
        $from   = $request->get('from');
        $string = $request->get('search');

        /** @var $resultProvider ResultStatisticsProvider */
        $resultProvider = $this->get('oro_search.provider.result_statistics_provider');

        return array(
            'from'           => $from,
            'searchString'   => $string,
            'groupedResults' => $resultProvider->getGroupedResults($string),
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.activemq.artemis.dto;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.activemq.artemis.utils.PasswordMaskingUtil;

@XmlRootElement(name = "connector")
@XmlAccessorType(XmlAccessType.FIELD)
public class JMXConnectorDTO {

   @XmlAttribute  (name = "connector-host")
   String connectorHost;

   @XmlAttribute  (name = "connector-port", required = true)
   Integer connectorPort;

   @XmlAttribute  (name = "rmi-registry-port")
   Integer rmiRegistryPort;

   @XmlAttribute  (name = "jmx-realm")
   String jmxRealm;

   @XmlAttribute  (name = "object-name")
   String objectName;

   @XmlAttribute (name = "authenticator-type")
   String authenticatorType;

   @XmlAttribute (name = "secured")
   Boolean secured;

   @XmlAttribute (name = "key-store-provider")
   String keyStoreProvider;

   @XmlAttribute (name = "key-store-path")
   String keyStorePath;

   @XmlAttribute (name = "key-store-password")
   String keyStorePassword;

   @XmlAttribute (name = "trust-store-provider")
   String trustStoreProvider;

   @XmlAttribute (name = "trust-store-path")
   String trustStorePath;

   @XmlAttribute (name = "trust-store-password")
   String trustStorePassword;

   @XmlAttribute (name = "password-codec")
   String passwordCodec;

   public String getConnectorHost() {
      return connectorHost;
   }

   public int getConnectorPort() {
      return connectorPort;
   }

   public Integer getRmiRegistryPort() {
      return rmiRegistryPort;
   }

   public String getJmxRealm() {
      return jmxRealm;
   }

   public String getObjectName() {
      return objectName;
   }

   public String getAuthenticatorType() {
      return authenticatorType;
   }

   public Boolean isSecured() {
      return secured;
   }

   public String getKeyStoreProvider() {
      return keyStoreProvider;
   }

   public String getKeyStorePath() {
      return keyStorePath;
   }

   public String getKeyStorePassword() throws Exception {
      return getPassword(keyStorePassword);
   }

   public String getTrustStoreProvider() {
      return trustStoreProvider;
   }

   public String getTrustStorePath() {
      return trustStorePath;
   }

   public String getTrustStorePassword() throws Exception {
      return getPassword(trustStorePassword);
   }

   private String getPassword(String password) throws Exception {
      return PasswordMaskingUtil.resolveMask(null, password, this.passwordCodec);
   }
}


text:
'use strict';

//Setting up route
angular.module('mean.listings').config(['$stateProvider',
  function($stateProvider) {
    // Check if the user is connected
    var checkLoggedin = function($q, $timeout, $http, $location) {
      // Initialize a new promise
      var deferred = $q.defer();

      // Make an AJAX call to check if the user is logged in
      $http.get('/loggedin').success(function(user) {
        // Authenticated
        if (user !== '0') $timeout(deferred.resolve);

        // Not Authenticated
        else {
          $timeout(deferred.reject);
          $location.url('/login');
        }
      });

      return deferred.promise;
    };

    // states for my app
    $stateProvider
      .state('all listings', {
        url: '/listings',
        templateUrl: 'listings/views/list.html',
        resolve: {
          loggedin: checkLoggedin
        }
      })
      .state('create listing', {
        url: '/listings/create',
        templateUrl: 'listings/views/create.html',
        resolve: {
          loggedin: checkLoggedin
        }
      })
      .state('edit listing', {
        url: '/listings/:listingId/edit',
        templateUrl: 'listings/views/edit.html',
        resolve: {
          loggedin: checkLoggedin
        }
      })
      .state('listing by id', {
        url: '/listings/:listingId',
        templateUrl: 'listings/views/view.html',
        resolve: {
          loggedin: checkLoggedin
        }
      });
  }
]);


text:
> Wi-Fi (or WiFi) is a local area wireless computer networking technology that allows electronic devices to connect to the network, mainly using the 2.4 gigahertz (12 cm) UHF and 5 gigahertz (6 cm) SHF ISM radio bands. Wikipedia

> Intel Edison Features

> > Wi-Fi peer-to-peer connectivity with Wi-Fi Direct, Allows two Intel® Edison devices (or one Intel® Edison device and a smartphone) to create a direct Wi-Fi connection to each other without an access point.

> > Wi-Fi multirole, Allows a connection to an access point simultaneously with Wi-Fi Direct operation.

> > Wi-Fi IBSS mode, Allows creation of multinode ad hoc networks that contain no access point.

- [WiFi Wikipedia](https://en.wikipedia.org/wiki/Wi-Fi)
- [Intel® Edison Boards Wi-Fi User Guide](http://www.intel.com/support/edison/sb/CS-035380.htm)
- [Intel® Edison Network Access](https://software.intel.com/en-us/connecting-to-a-network-intel-edison-board)
- [Edison Wi-Fi Configuration](http://rwx.io/blog/2015/08/16/edison-wifi-config/)
- [Realtek 8192 chipset driver, ported to kernel 3.11](https://github.com/pvaret/rtl8192cu-fixes)

## Kernel Integration

### Kernel Display Message

```sh
    root@edison:~# dmesg | grep -i wifi
    [    0.189658] Using generic wifi platform data
    [    0.189675] wifi_platform_data: GPIO == 64
    [    3.850154] found wifi platform device wlan
    [    4.171606] wifi_platform_set_power = 1
    [    4.373687] wifi_platform_bus_enumerate device present 1
    [    4.412928] wifi_platform_get_mac_addr
    [    4.413069] wifi_get_mac_addr_intel: unable to open /config/wifi/mac.txt
    [    4.420354] wifi_platform_set_power = 0
    [    4.421428] wifi_platform_bus_enumerate device present 0
    [   38.194385] wl_android_wifi_on in
    [   38.194403] wifi_platform_set_power = 1
    [   39.117444] wifi_platform_get_mac_addr
    [   39.117488] wifi_get_mac_addr_intel: unable to open /config/wifi/mac.txt
```

### Kernel Modules

```sh
    root@edison:~# lsmod
    Module                  Size  Used by0
    usb_f_acm              14335  1
    ...
    bcm_bt_lpm             13708  0
    bcm4334x              587105  0
```

## Applications / Libraries

> RFKill
> > rfkill is a small userspace tool to query the state of the rfkill switches, buttons and subsystem interfaces. Some devices come with a hard switch that lets you kill different types of RF radios: 802.11 / Bluetooth / NFC / UWB / WAN / WIMAX / FM. Some times these buttons may kill more than one RF type. The Linux kernel rfkill subsystem exposes these hardware buttons and lets userspace query its status and set its status through a /dev/rfkill. Given that at times some RF devices do not have hardware rfkill buttons rfkill the Linux kernel also exposes software rfkill capabilities that allows userspace to mimic a hardware rfkill event and turn on or off RF.  [Rfkill Homepage](https://wireless.wiki.kernel.org/en/users/documentation/rfkill)

```sh
    root@edison:~# rfkill list
    0: phy0: wlan
            Soft blocked: no
            Hard blocked: no
    1: brcmfmac-wifi: wlan
            Soft blocked: no
            Hard blocked: no
    2: bcm43xx Bluetooth: bluetooth
            Soft blocked: yes
            Hard blocked: no
```

### Usage Models, Ubilinux

```sh
    edison@ubilinux:~$ su
    Password: edison
    root@ubilinux:/home/edison# cd
    root@ubilinux:~# nano /etc/network/interfaces
    # interfaces(5) file used by ifup(8) and ifdown(8)
    auto lo
    iface lo inet loopback

    #auto usb0
    #iface usb0 inet static
    #    address 192.168.2.15
    #    netmask 255.255.255.0

    auto wlan0
    iface wlan0 inet dhcp
        # For WPA
        wpa-ssid INFINITUMxxxx
        wpa-psk yyyy
        # For WEP
        #wireless-essid itesm
        #wireless-mode Managed
        #wireless-key s:""

    root@ubilinux:~# ifup wlan0
    root@ubilinux:~# reboot

    <reboot your board, sign in and become root>
```

### Usage Models, Yocto

#### Default Configuration

```sh
    root@Edison:~# configure_edison --wifi
     Configure Edison: WiFi Connection
    root@edison:~# ifconfig
     lo        Link encap:Local Loopback
               inet addr:127.0.0.1  Mask:255.0.0.0
     ...
     usb0      Link encap:Ethernet  HWaddr 5a:2a:15:c5:5f:7b
               inet addr:192.168.2.15  Bcast:192.168.2.255  Mask:255.255.255.0
     ...
     wlan0     Link encap:Ethernet  HWaddr 78:4b:87:a6:cf:5e
               inet addr:192.168.1.68  Bcast:0.0.0.0  Mask:255.255.255.0
    root@edison:~# ping -c 3 8.8.8.8
    PING google.com (173.194.115.196): 56 data bytes
    64 bytes from 173.194.115.196: seq=0 ttl=58 time=28.487 ms
    64 bytes from 173.194.115.196: seq=1 ttl=58 time=29.391 ms
    64 bytes from 173.194.115.196: seq=2 ttl=58 time=29.773 ms

    --- google.com ping statistics ---
    3 packets transmitted, 3 packets received, 0% packet loss
    round-trip min/avg/max = 28.487/29.217/29.773 ms
    root@edison:~#
```

#### Persistent Connection

```sh
    root@edison:~# configure_edison -wifi
    ...
    root@edison:~# systemctl enable wpa_supplicant
    root@edison:~# systemctl start wpa_supplicant
```

#### Manual Persistent Configuration

Make sure there are no soft blocks

```sh
    root@edison:~# rfkill list
```

Make sure wlan0 is loaded and see IP

```sh
    root@edison:~# ifconfig
```

Load the wlan0 device driver

```sh
    root@edison:~# wpa_supplicant -B -Dnl80211 -iwlan0 -c/etc/wpa_supplicant/wpa_supplicant.conf
```

Get DHCP and DNS

```sh
    root@edison:~# busybox udhcpc -i wlan0
```

Move usb0 to a different non-conflicting subnet

```sh
    root@edison:~# vi /etc/system/system/basic.target.wants/network-gadget-init.service
```

Disable usb0 device from loading

```sh
    root@edison:~# systemctl disable network-gadget-init.service
```

Ensure there is a wpa_supplicant network{} definition and remove unneeded networks

```sh
    root@edison:~# vi /etc/wpa_supplicant/wpa_supplicant.conf
```

Enable first network definition

```sh
    root@edison:~# wpa_cli
         > enable_network 0
         > select_network 0
         > save
         > quit
```

Example WEP key wpa_supplicant.conf

```sh
    ctrl_interface=/var/run/wpa_supplicant
    ctrl_interface_group=0
    update_config=1
    network={
         ssid="YOURSSID"
         scan_ssid=1
         key_mgmt=NONE
         auth_alg=OPEN
         wep_key0=f0039faded348299992344be23
    }
```

Remove soft block on wlan0

```sh
    root@edison:~# rfkill unblock wlan
```

Enable wifi on boot once config is confirmed correct

```sh
    root@edison:~# systemctl enable wa_supplicant
```

WiFi to connect at power up:

```sh
    systemctl enable wpa_supplicant
    systemctl start wpa_supplicant
```

### Password Lenght

> ... I am asked for a 5 or 13 character network password, but my network's password is 10 characters long ... [Edison WiFi setup - password must be either 5 or 13 characters](https://communities.intel.com/thread/59888?start=0&tstart=0)

```sh
--- configure_edison.orig
+++ configure_edison
@@ -60,6 +60,15 @@
   wep_key0="%s"
}
'''
+  WEP_26HEX =  '''
+network={
+  ssid="%s"
+  %s
+  key_mgmt=NONE
+  group=WEP104 WEP40
+  wep_key0=%s
+}
+'''
   WPAPSK =  '''
network={
   ssid="%s"
@@ -359,10 +368,13 @@
       return wpa_templates.OPEN % (ssid, "scan_ssid=1")
     elif security == 1:
       password = ''
-      while len(password) != 5 and len(password) != 13:
-        print "Password must be either 5 or 13 characters."
+      while len(password) != 5 and len(password) != 13 and len(password) != 26:
+        print "Password must be either 5 or 13 ascii characters or 26 hex."
         password = getNetworkPassword()
-      return wpa_templates.WEP % (ssid, "scan_ssid=1", password)
+        if len(password) == 26:
+          return wpa_templates.WEP_26HEX % (ssid, "scan_ssid=1", password)
+        else:
+          return wpa_templates.WEP % (ssid, "scan_ssid=1", password)
     elif security == 2:
       password = ''
       while len(password) < 8 or len(password) > 63:
@@ -384,10 +396,13 @@
     return wpa_templates.OPEN % (ssid, "")
   elif network_map[ssid] == "WEP":
     password = ''
-    while len(password) != 5 and len(password) != 13:
-        print "Password must be either 5 or 13 characters."
+    while len(password) != 5 and len(password) != 13 and len(password) != 26:
+        print "Password must be either 5 or 13 ascii characters or 26 hex."
         password = getNetworkPassword()
-    return wpa_templates.WEP % (ssid, "", password)
+        if len(password) == 26:
+          return wpa_templates.WEP_26HEX % (ssid, "", password)
+        else:
+          return wpa_templates.WEP % (ssid, "", password)
   elif network_map[ssid] == "WPA-PSK":
     password = ''
     while len(password) < 8 or len(password) > 63:
@@ -409,10 +424,13 @@
     return wpa_templates.OPEN % (ssid, "scan_ssid=1")
   elif protocol == "WEP":
     password = changewifi[2]
-    if len(password) != 5 and len(password) != 13:
-        print "Password must be either 5 or 13 characters."
+    if len(password) != 5 and len(password) != 13 and len(password) != 26:
+        print "Password must be either 5 or 13 ascii characters or 26 hex."
         return None
-    return wpa_templates.WEP % (ssid, "scan_ssid=1", password)
+    if len(password) == 26:
+      return wpa_templates.WEP_26HEX % (ssid, "scan_ssid=1", password)
+    else:
+      return wpa_templates.WEP % (ssid, "scan_ssid=1", password)
   elif protocol == "WPA-PSK":
     password = changewifi[2]
     if len(password) < 8 or len(password) > 63:
```

### Mode Access Point @ Ubilinux

- [Ubilinux Access Point Hostapd](http://www.emutexlabs.com/forum/ubilinux/85-ubilinux-access-point-hostapd)

## Testing

ToDo iPerf ...


text:
<!DOCTYPE html>

  <!DOCTYPE html>

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

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta property="og:url" content="http://alienmouth.com/march2016/7.html" />
  <meta property="og:description" content="Alien Mouth publishes writing and audio/visual art" />
  <meta property="og:type" content="article" />
  <meta property="og:title" content="Fever in Kabul" />
  <meta property="og:image" content="http://alienmouth.com/assets/img/og_image.png" />
  <meta property="og:site_name" content="Alien Mouth">

  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:site" content="@alienmouth" />
  <meta name="twitter:title" content="Fever in Kabul" />
  <meta name="twitter:description" content="Alien Mouth publishes writing and audio/visual art" />
  <meta name="twitter:image" content="http://alienmouth.com/assets/img/twitter.png" />

  <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
  <link rel="manifest" href="/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <title>Fever in Kabul</title>
  <meta name="description" content="A man walkssicklyunder umbrella,and the storm is sandy,according to CNN:it is a time to come,indeterminate;it is Kabul,in summer, maybe:World Water Monopolyf...">

    <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

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

  <link rel="canonical" href="/march2016/7.html">

  <link rel="alternate" type="application/rss+xml" title="Alien Mouth" href="/feed.xml" />

		journal
		reviews
		books
		about
		connect
		submit

Fever in Kabul

by TS Hidalgo on March 19, 2016

A man walks

sickly

under umbrella,

and the storm is sandy,

according to CNN:

it is a time to come,

indeterminate;

it is Kabul,

in summer, maybe:

World Water Monopoly

flies (triumphant) this time

on its carpets

on, maybe,

neighboring Persia:

the Markets are not to take

to suddenly turn upward.

    Fever in Kabul - March 19, 2016 -

	<gcse:search></gcse:search>


text:
package edacc.parametergrapheditor;

import edacc.EDACCApp;
import edacc.parameterspace.Parameter;
import edacc.parameterspace.domain.Domain;
import edacc.parameterspace.domain.OrdinalDomain;
import java.util.LinkedList;

/**
 *
 * @author simon
 */
public class SpecifyOrdinalDomainPanel extends SpecifyCategoricalDomainPanel {
    public SpecifyOrdinalDomainPanel(SpecifyDomainDialog main) {
        super(main);
    }

    @Override
    public Domain getDomain() throws InvalidDomainException {
        if (model.isEmpty()) {
            throw new InvalidDomainException("You must specify at least one category for ordinal domain.");
        }
        LinkedList<String> list = new LinkedList<String>();
        for (int i = 0; i < model.size(); i++) {
            list.add((String) model.get(i));
        }
        return new OrdinalDomain(list);
    }

    @Override
    public void setDomain(Domain orDomain, Domain andDomain) {
        if (!(orDomain instanceof OrdinalDomain) || andDomain != null) {
            return;
        }
        model.clear();
        for (String s : ((OrdinalDomain) orDomain).getOrdered_list()) {
            model.addElement(s);
        }
    }

    @Override
    public void useDomain() {
        UseDomainDialog dialog = new UseDomainDialog(EDACCApp.getApplication().getMainFrame(), true, main.getParameters(), OrdinalDomain.class);
        dialog.setName("UseDomainDialog");
        EDACCApp.getApplication().show(dialog);
        Parameter p;
        if ((p = dialog.getSelectedItem()) != null && p.getDomain() instanceof OrdinalDomain) {
            this.setDomain(p.getDomain(), null);
        }
    }

}


text:
package org.apache.hadoop.tools.posum.common.records.dataentity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.hadoop.conf.Configuration;

import java.util.Map;

public interface JobConfProxy extends GeneralDataEntity<JobConfProxy> {

  @JsonIgnore
  String getEntry(String name);

  @JsonIgnore
  Configuration getConf();

  void setConf(Configuration conf);

  String getConfPath();

  void setConfPath(String confPath);

  @JsonIgnore
  Map<String, String> getPropertyMap();

  void setPropertyMap(Map<String, String> propertyMap);
}


text:
<ion-view title="Search">
  <ion-nav-buttons side="left">
    <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  </ion-nav-buttons>
  <ion-content class="has-header">
  </ion-content>
</ion-view>


text:
#ifndef itkGrayscaleErodeImageFilter_h
#define itkGrayscaleErodeImageFilter_h

#include "itkKernelImageFilter.h"
#include "itkMovingHistogramErodeImageFilter.h"
#include "itkBasicErodeImageFilter.h"
#include "itkAnchorErodeImageFilter.h"
#include "itkVanHerkGilWermanErodeImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkConstantBoundaryCondition.h"
#include "itkNeighborhood.h"

namespace itk
{
/**
 * \class GrayscaleErodeImageFilter
 * \brief Grayscale erosion of an image.
 *
 * Erode an image using grayscale morphology. Erosion takes the
 * maximum of all the pixels identified by the structuring element.
 *
 * The structuring element is assumed to be composed of binary
 * values (zero or one). Only elements of the structuring element
 * having values > 0 are candidates for affecting the center pixel.
 *
 * \sa MorphologyImageFilter, GrayscaleFunctionErodeImageFilter, BinaryErodeImageFilter
 * \ingroup ImageEnhancement  MathematicalMorphologyImageFilters
 * \ingroup ITKMathematicalMorphology
 *
 * \wiki
 * \wikiexample{Morphology/GrayscaleErodeImageFilter,Erode a grayscale image}
 * \endwiki
 */

template< typename TInputImage, typename TOutputImage, typename TKernel >
class ITK_TEMPLATE_EXPORT GrayscaleErodeImageFilter:
  public KernelImageFilter< TInputImage, TOutputImage, TKernel >
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(GrayscaleErodeImageFilter);

  /** Standard class type aliases. */
  using Self = GrayscaleErodeImageFilter;
  using Superclass = KernelImageFilter< TInputImage, TOutputImage, TKernel >;
  using Pointer = SmartPointer< Self >;
  using ConstPointer = SmartPointer< const Self >;

  /** Standard New method. */
  itkNewMacro(Self);

  /** Runtime information support. */
  itkTypeMacro(GrayscaleErodeImageFilter,
               KernelImageFilter);

  /** Image related type alias. */
  static constexpr unsigned int ImageDimension = TInputImage::ImageDimension;

  /** Image related type alias. */
  using InputImageType = TInputImage;
  using OutputImageType = TOutputImage;
  using RegionType = typename TInputImage::RegionType;
  using SizeType = typename TInputImage::SizeType;
  using IndexType = typename TInputImage::IndexType;
  using PixelType = typename TInputImage::PixelType;
  using OffsetType = typename TInputImage::OffsetType;
  using OutputImageRegionType = typename Superclass::OutputImageRegionType;

  /** define values used to determine which algorithm to use */
  enum AlgorithmType {
    BASIC = 0,
    HISTO = 1,
    ANCHOR = 2,
    VHGW = 3
    };

  using HistogramFilterType =
      MovingHistogramErodeImageFilter< TInputImage, TOutputImage, TKernel >;
  using BasicFilterType =
      BasicErodeImageFilter< TInputImage, TOutputImage, TKernel >;

  using FlatKernelType = FlatStructuringElement< Self::ImageDimension >;

  using AnchorFilterType = AnchorErodeImageFilter< TInputImage, FlatKernelType >;
  using VHGWFilterType = VanHerkGilWermanErodeImageFilter< TInputImage, FlatKernelType >;
  using CastFilterType = CastImageFilter< TInputImage, TOutputImage >;

  /** Typedef for boundary conditions. */
  using ImageBoundaryConditionPointerType = ImageBoundaryCondition< InputImageType > *;
  using ImageBoundaryConditionConstPointerType = const ImageBoundaryCondition<InputImageType> *;
  using DefaultBoundaryConditionType = ConstantBoundaryCondition< InputImageType >;

  /** Kernel type alias. */
  using KernelType = TKernel;
//   using KernelSuperclass = typename KernelType::Superclass;
//   using KernelSuperclass = Neighborhood< typename KernelType::PixelType, ImageDimension >;

  /** Set kernel (structuring element). */
  void SetKernel(const KernelType & kernel) override;

  /** Set/Get the boundary value. */
  void SetBoundary(const PixelType value);

  itkGetConstMacro(Boundary, PixelType);

  /** Set/Get the backend filter class. */
  void SetAlgorithm(int algo);

  itkGetConstMacro(Algorithm, int);

  /** GrayscaleErodeImageFilter need to set its internal filters as modified */
  void Modified() const override;

  void SetNumberOfWorkUnits(ThreadIdType nb) override;

protected:
  GrayscaleErodeImageFilter();
  ~GrayscaleErodeImageFilter() override = default;
  void PrintSelf(std::ostream & os, Indent indent) const override;

  void GenerateData() override;

private:
  PixelType m_Boundary;

  // the filters used internally
  typename HistogramFilterType::Pointer m_HistogramFilter;

  typename BasicFilterType::Pointer m_BasicFilter;

  typename AnchorFilterType::Pointer m_AnchorFilter;

  typename VHGWFilterType::Pointer m_VHGWFilter;

  // and the name of the filter
  int m_Algorithm;

  // the boundary condition need to be stored here
  DefaultBoundaryConditionType m_BoundaryCondition;
}; // end of class
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkGrayscaleErodeImageFilter.hxx"
#endif

#endif


text:
.. _configuration:

***********************
Configuration Variables
***********************

At runtime, there are a several configuration variables that can be used to change the behavior of CoolProp

.. warning:: The adjustment of the internal configuration variables might have side effects that you are not expecting, use with caution!!

From C++ and the SWIG wrappers, the values can be directly set/changed by using the type-specified getter/setter functions :cpapi:`get_config_bool`, :cpapi:`set_config_bool`, :cpapi:`get_config_string`, :cpapi:`set_config_string`, etc., as in something like:

.. ipython::

    In [0]: import CoolProp.CoolProp as CP

    In [1]: current_val = CP.get_config_bool(CP.CRITICAL_WITHIN_1UK)

    In [1]: CP.set_config_bool(CP.CRITICAL_WITHIN_1UK, current_val)

From all languages, the configuration state can obtained by retrieving the configuration state in the form of a  `JSON <http://json.org/>`_ formatted string.  For instance, in python, you can get the default configuration state from

.. ipython::

    In [0]: import CoolProp.CoolProp as CP, json

    In [1]: json.loads(CP.get_config_as_json_string())

Most modern languages have facilities for interfacing with JSON formatted strings and converting them back and forth with language-specific data structures.  For instance, in python, there is the built-in ``json`` package that converts json-formatted strings to python dictionaries, lists, etc.

Configuration Keys
------------------

Here is a list of (alphabetically sorted) configuration keys that can be used, along with a short description of the use of each of the configuration keys:

.. include :: configuration_keys.rst.in


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Fl. bulg. suppl. 40. 1898

#### Original name
null

### Remarks
null


text:
from abc import ABCMeta, abstractmethod
from collections import Iterable, OrderedDict

from six import add_metaclass
import numpy as np

from openmc.checkvalue import check_type

@add_metaclass(ABCMeta)
class Region(object):
    """Region of space that can be assigned to a cell.

    Region is an abstract base class that is inherited by
    :class:`openmc.Halfspace`, :class:`openmc.Intersection`,
    :class:`openmc.Union`, and :class:`openmc.Complement`. Each of those
    respective classes are typically not instantiated directly but rather are
    created through operators of the Surface and Region classes.

    """
    def __and__(self, other):
        return Intersection(self, other)

    def __or__(self, other):
        return Union(self, other)

    def __invert__(self):
        return Complement(self)

    @abstractmethod
    def __contains__(self, point):
        return False

    @abstractmethod
    def __str__(self):
        return ''

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return False
        elif str(self) != str(other):
            return False
        else:
            return True

    def __ne__(self, other):
        return not self == other

    def get_surfaces(self, surfaces=None):
        """
        Recursively find all the surfaces referenced by a region and return them

        Parameters
        ----------
        surfaces: collections.OrderedDict, optional
            Dictionary mapping surface IDs to :class:`openmc.Surface` instances

        Returns
        -------
        surfaces: collections.OrderedDict
            Dictionary mapping surface IDs to :class:`openmc.Surface` instances

        """
        if surfaces is None:
            surfaces = OrderedDict()
        for region in self:
            surfaces = region.get_surfaces(surfaces)
        return surfaces

    @staticmethod
    def from_expression(expression, surfaces):
        """Generate a region given an infix expression.

        Parameters
        ----------
        expression : str
            Boolean expression relating surface half-spaces. The possible
            operators are union '|', intersection ' ', and complement '~'. For
            example, '(1 -2) | 3 ~(4 -5)'.
        surfaces : dict
            Dictionary whose keys are suface IDs that appear in the Boolean
            expression and whose values are Surface objects.

        """

        # Strip leading and trailing whitespace
        expression = expression.strip()

        # Convert the string expression into a list of tokens, i.e., operators
        # and surface half-spaces, representing the expression in infix
        # notation.
        i = 0
        i_start = -1
        tokens = []
        while i < len(expression):
            if expression[i] in '()|~ ':
                # If special character appears immediately after a non-operator,
                # create a token with the apporpriate half-space
                if i_start >= 0:
                    j = int(expression[i_start:i])
                    if j < 0:
                        tokens.append(-surfaces[abs(j)])
                    else:
                        tokens.append(+surfaces[abs(j)])

                if expression[i] in '()|~':
                    # For everything other than intersection, add the operator
                    # to the list of tokens
                    tokens.append(expression[i])
                else:
                    # Find next non-space character
                    while expression[i+1] == ' ':
                        i += 1

                    # If previous token is a halfspace or right parenthesis and next token
                    # is not a left parenthese or union operator, that implies that the
                    # whitespace is to be interpreted as an intersection operator
                    if (i_start >= 0 or tokens[-1] == ')') and \
                       expression[i+1] not in ')|':
                        tokens.append(' ')

                i_start = -1
            else:
                # Check for invalid characters
                if expression[i] not in '-+0123456789':
                    raise SyntaxError("Invalid character '{}' in expression"
                                      .format(expression[i]))

                # If we haven't yet reached the start of a word, start one
                if i_start < 0:
                    i_start = i
            i += 1

        # If we've reached the end and we're still in a word, create a
        # half-space token and add it to the list
        if i_start >= 0:
            j = int(expression[i_start:])
            if j < 0:
                tokens.append(-surfaces[abs(j)])
            else:
                tokens.append(+surfaces[abs(j)])

        # The functions below are used to apply an operator to operands on the
        # output queue during the shunting yard algorithm.
        def can_be_combined(region):
            return isinstance(region, Complement) or hasattr(region, 'surface')

        def apply_operator(output, operator):
            r2 = output.pop()
            if operator == ' ':
                r1 = output.pop()
                if isinstance(r1, Intersection) and can_be_combined(r2):
                    r1.nodes.append(r2)
                    output.append(r1)
                elif isinstance(r2, Intersection) and can_be_combined(r1):
                    r2.nodes.insert(0, r1)
                    output.append(r2)
                elif isinstance(r1, Intersection) and isinstance(r2, Intersection):
                    r1.nodes += r2.nodes
                    output.append(r1)
                else:
                    output.append(Intersection(r1, r2))
            elif operator == '|':
                r1 = output.pop()
                if isinstance(r1, Union) and can_be_combined(r2):
                    r1.nodes.append(r2)
                    output.append(r1)
                elif isinstance(r2, Union) and can_be_combined(r1):
                    r2.nodes.insert(0, r1)
                    output.append(r2)
                elif isinstance(r1, Union) and isinstance(r2, Union):
                    r1.nodes += r2.nodes
                    output.append(r1)
                else:
                    output.append(Union(r1, r2))
            elif operator == '~':
                output.append(Complement(r2))

        # The following is an implementation of the shunting yard algorithm to
        # generate an abstract syntax tree for the region expression.
        output = []
        stack = []
        precedence = {'|': 1, ' ': 2, '~': 3}
        associativity = {'|': 'left', ' ': 'left', '~': 'right'}
        for token in tokens:
            if token in (' ', '|', '~'):
                # Normal operators
                while stack:
                    op = stack[-1]
                    if (op not in ('(', ')') and
                        ((associativity[token] == 'right' and
                          precedence[token] < precedence[op]) or
                         (associativity[token] == 'left' and
                          precedence[token] <= precedence[op]))):
                        apply_operator(output, stack.pop())
                    else:
                        break
                stack.append(token)
            elif token == '(':
                # Left parentheses
                stack.append(token)
            elif token == ')':
                # Right parentheses
                while stack[-1] != '(':
                    apply_operator(output, stack.pop())
                    if len(stack) == 0:
                        raise SyntaxError('Mismatched parentheses in '
                                          'region specification.')
                stack.pop()
            else:
                # Surface halfspaces
                output.append(token)
        while stack:
            if stack[-1] in '()':
                raise SyntaxError('Mismatched parentheses in region '
                                  'specification.')
            apply_operator(output, stack.pop())

        # Since we are generating an abstract syntax tree rather than a reverse
        # Polish notation expression, the output queue should have a single item
        # at the end
        return output[0]

class Intersection(Region):
    r"""Intersection of two or more regions.

    Instances of Intersection are generally created via the __and__ operator
    applied to two instances of :class:`openmc.Region`. This is illustrated in
    the following example:

    >>> equator = openmc.ZPlane(z0=0.0)
    >>> earth = openmc.Sphere(R=637.1e6)
    >>> northern_hemisphere = -earth & +equator
    >>> southern_hemisphere = -earth & -equator
    >>> type(northern_hemisphere)
    <class 'openmc.region.Intersection'>

    Parameters
    ----------
    \*nodes
        Regions to take the intersection of

    Attributes
    ----------
    nodes : list of openmc.Region
        Regions to take the intersection of
    bounding_box : tuple of numpy.array
        Lower-left and upper-right coordinates of an axis-aligned bounding box

    """

    def __init__(self, *nodes):
        self.nodes = list(nodes)

    def __and__(self, other):
        new = Intersection(*self.nodes)
        new.nodes.append(other)
        return new

    def __iter__(self):
        for n in self.nodes:
            yield n

    def __contains__(self, point):
        """Check whether a point is contained in the region.

        Parameters
        ----------
        point : 3-tuple of float
            Cartesian coordinates, :math:`(x',y',z')`, of the point

        Returns
        -------
        bool
            Whether the point is in the region

        """
        return all(point in n for n in self.nodes)

    def __str__(self):
        return '(' + ' '.join(map(str, self.nodes)) + ')'

    @property
    def nodes(self):
        return self._nodes

    @property
    def bounding_box(self):
        lower_left = np.array([-np.inf, -np.inf, -np.inf])
        upper_right = np.array([np.inf, np.inf, np.inf])
        for n in self.nodes:
            lower_left_n, upper_right_n = n.bounding_box
            lower_left[:] = np.maximum(lower_left, lower_left_n)
            upper_right[:] = np.minimum(upper_right, upper_right_n)
        return lower_left, upper_right

    @nodes.setter
    def nodes(self, nodes):
        check_type('nodes', nodes, Iterable, Region)
        self._nodes = nodes

class Union(Region):
    r"""Union of two or more regions.

    Instances of Union are generally created via the __or__ operator applied to
    two instances of :class:`openmc.Region`. This is illustrated in the
    following example:

    >>> s1 = openmc.ZPlane(z0=0.0)
    >>> s2 = openmc.Sphere(R=637.1e6)
    >>> type(-s2 | +s1)
    <class 'openmc.region.Union'>

    Parameters
    ----------
    \*nodes
        Regions to take the union of

    Attributes
    ----------
    nodes : tuple of openmc.Region
        Regions to take the union of
    bounding_box : 2-tuple of numpy.array
        Lower-left and upper-right coordinates of an axis-aligned bounding box

    """

    def __init__(self, *nodes):
        self.nodes = list(nodes)

    def __or__(self, other):
        new = Union(*self.nodes)
        new.nodes.append(other)
        return new

    def __iter__(self):
        for n in self.nodes:
            yield n

    def __contains__(self, point):
        """Check whether a point is contained in the region.

        Parameters
        ----------
        point : 3-tuple of float
            Cartesian coordinates, :math:`(x',y',z')`, of the point

        Returns
        -------
        bool
            Whether the point is in the region

        """
        return any(point in n for n in self.nodes)

    def __str__(self):
        return '(' + ' | '.join(map(str, self.nodes)) + ')'

    @property
    def nodes(self):
        return self._nodes

    @property
    def bounding_box(self):
        lower_left = np.array([np.inf, np.inf, np.inf])
        upper_right = np.array([-np.inf, -np.inf, -np.inf])
        for n in self.nodes:
            lower_left_n, upper_right_n = n.bounding_box
            lower_left[:] = np.minimum(lower_left, lower_left_n)
            upper_right[:] = np.maximum(upper_right, upper_right_n)
        return lower_left, upper_right

    @nodes.setter
    def nodes(self, nodes):
        check_type('nodes', nodes, Iterable, Region)
        self._nodes = nodes

class Complement(Region):
    """Complement of a region.

    The Complement of an existing :class:`openmc.Region` can be created by using
    the __invert__ operator as the following example demonstrates:

    >>> xl = openmc.XPlane(x0=-10.0)
    >>> xr = openmc.XPlane(x0=10.0)
    >>> yl = openmc.YPlane(y0=-10.0)
    >>> yr = openmc.YPlane(y0=10.0)
    >>> inside_box = +xl & -xr & +yl & -yl
    >>> outside_box = ~inside_box
    >>> type(outside_box)
    <class 'openmc.region.Complement'>

    Parameters
    ----------
    node : openmc.Region
        Region to take the complement of

    Attributes
    ----------
    node : openmc.Region
        Regions to take the complement of
    bounding_box : tuple of numpy.array
        Lower-left and upper-right coordinates of an axis-aligned bounding box

    """

    def __init__(self, node):
        self.node = node

    def __contains__(self, point):
        """Check whether a point is contained in the region.

        Parameters
        ----------
        point : 3-tuple of float
            Cartesian coordinates, :math:`(x',y',z')`, of the point

        Returns
        -------
        bool
            Whether the point is in the region

        """
        return point not in self.node

    def __str__(self):
        return '~' + str(self.node)

    @property
    def node(self):
        return self._node

    @node.setter
    def node(self, node):
        check_type('node', node, Region)
        self._node = node

    @property
    def bounding_box(self):
        # Use De Morgan's laws to distribute the complement operator so that it
        # only applies to surface half-spaces, thus allowing us to calculate the
        # bounding box in the usual recursive manner.
        if isinstance(self.node, Union):
            temp_region = Intersection(*[~n for n in self.node.nodes])
        elif isinstance(self.node, Intersection):
            temp_region = Union(*[~n for n in self.node.nodes])
        elif isinstance(self.node, Complement):
            temp_region = self.node.node
        else:
            temp_region = ~self.node
        return temp_region.bounding_box

    def get_surfaces(self, surfaces=None):
        """
        Recursively find and return all the surfaces referenced by the node

        Parameters
        ----------
        surfaces: collections.OrderedDict, optional
            Dictionary mapping surface IDs to :class:`openmc.Surface` instances

        Returns
        -------
        surfaces: collections.OrderedDict
            Dictionary mapping surface IDs to :class:`openmc.Surface` instances

        """
        if surfaces is None:
            surfaces = OrderedDict()
        for region in self.node:
            surfaces = region.get_surfaces(surfaces)
        return surfaces


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.apple;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.DefaultLabelConverter;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.common.options.Converters.CommaSeparatedOptionListConverter;
import com.google.devtools.common.options.EnumConverter;
import com.google.devtools.common.options.Option;

import java.util.List;

/**
 * Command-line options for building for Apple platforms.
 */
public class AppleCommandLineOptions extends FragmentOptions {

  @Option(
    name = "xcode_version",
    defaultValue = "null",
    category = "build",
    converter = DottedVersionConverter.class,
    help =
        "If specified, uses xcode of the given version for relevant build actions. "
            + "If unspecified, uses the executor default version of xcode."
  )
  // TODO(bazel-team): This should be of String type, to allow referencing an alias based
  // on an xcode_config target.
  public DottedVersion xcodeVersion;

  @Option(
    name = "ios_sdk_version",
    // TODO(bazel-team): Make this flag optional, and infer SDKROOT based on executor default.
    defaultValue = DEFAULT_IOS_SDK_VERSION,
    converter = DottedVersionConverter.class,
    category = "build",
    help = "Specifies the version of the iOS SDK to use to build iOS applications."
  )
  public DottedVersion iosSdkVersion;

  @VisibleForTesting public static final String DEFAULT_IOS_SDK_VERSION = "8.4";

  @Option(name = "ios_cpu",
      defaultValue = DEFAULT_IOS_CPU,
      category = "build",
      help = "Specifies to target CPU of iOS compilation.")
  public String iosCpu;

  @Option(name = "ios_multi_cpus",
      converter = CommaSeparatedOptionListConverter.class,
      defaultValue = "",
      category = "flags",
      help = "Comma-separated list of architectures to build an ios_application with. The result "
          + "is a universal binary containing all specified architectures.")
  public List<String> iosMultiCpus;

  @VisibleForTesting static final String DEFAULT_IOS_CPU = "x86_64";

  @Option(name = "default_ios_provisioning_profile",
      defaultValue = "",
      category = "undocumented",
      converter = DefaultProvisioningProfileConverter.class)
  public Label defaultProvisioningProfile;

  @Option(name = "xcode_version_config",
      defaultValue = "",
      category = "undocumented",
      converter = XcodeVersionConfigConverter.class,
      help = "The label of the xcode_config rule to be used for selecting the xcode version "
          + "in the build configuration")
  public Label xcodeVersionConfig;

  /**
   * The default label of the build-wide {@code xcode_config} configuration rule. This can be
   * changed from the default using the {@code xcode_version_config} build flag.
   */
  static final String DEFAULT_XCODE_VERSION_CONFIG_LABEL =
      Constants.TOOLS_REPOSITORY + "//tools/objc:host_xcodes";

  /** Converter for --default_ios_provisioning_profile. */
  public static class DefaultProvisioningProfileConverter extends DefaultLabelConverter {
    public DefaultProvisioningProfileConverter() {
      super("//tools/objc:default_provisioning_profile");
    }
  }

  @Option(name = "apple_bitcode",
      converter = AppleBitcodeMode.Converter.class,
      // TODO(blaze-team): Default to embedded_markers when fully implemented.
      defaultValue = "none",
      category = "flags",
      help = "Specify the Apple bitcode mode for compile steps. "
             + "Values: 'none', 'embedded_markers', 'embedded'.")
  public AppleBitcodeMode appleBitcodeMode;

  /** Converter for {@code --xcode_version_config}. */
  public static class XcodeVersionConfigConverter extends DefaultLabelConverter {
    public XcodeVersionConfigConverter() {
      super(DEFAULT_XCODE_VERSION_CONFIG_LABEL);
    }
  }

  private Platform getPlatform() {
    for (String architecture : iosMultiCpus) {
      if (Platform.forIosArch(architecture) == Platform.IOS_DEVICE) {
        return Platform.IOS_DEVICE;
      }
    }
    return Platform.forIosArch(iosCpu);
  }

  @Override
  public void addAllLabels(Multimap<String, Label> labelMap) {
    if (getPlatform() == Platform.IOS_DEVICE) {
      labelMap.put("default_provisioning_profile", defaultProvisioningProfile);
    }
  }

  /**
   * Represents the Apple Bitcode mode for compilation steps.
   *
   *
Bitcode is an intermediate representation of a compiled program. For many platforms,
   * Apple requires app submissions to contain bitcode in order to be uploaded to the app store.
   *
   *
This is a build-wide value, as bitcode mode needs to be consistent among a target and
   * its compiled dependencies.
   */
  public enum AppleBitcodeMode {

    /**
     * Do not compile bitcode.
     */
    NONE("none"),
    /**
     * Compile the minimal set of bitcode markers. This is often the best option for
     * developer/debug builds.
     */
    EMBEDDED_MARKERS("embedded_markers", "-fembed-bitcode-marker"),
    /**
     * Fully embed bitcode in compiled files. This is often the best option for release builds.
     */
    EMBEDDED("embedded", "-fembed-bitcode");

    private final String mode;
    private final ImmutableList<String> compilerFlags;

    private AppleBitcodeMode(String mode, String... compilerFlags) {
      this.mode = mode;
      this.compilerFlags = ImmutableList.copyOf(compilerFlags);
    }

    @Override
    public String toString() {
      return mode;
    }

    /**
     * Returns the flags that should be added to compile actions to use this bitcode setting.
     */
    public ImmutableList<String> getCompilerFlags() {
      return compilerFlags;
    }

    /**
     * Converts to {@link AppleBitcodeMode}.
     */
    public static class Converter extends EnumConverter<AppleBitcodeMode> {
      public Converter() {
        super(AppleBitcodeMode.class, "apple bitcode mode");
      }
    }
  }

  @Override
  public FragmentOptions getHost(boolean fallback) {
    AppleCommandLineOptions host = (AppleCommandLineOptions) super.getHost(fallback);

    // Set options needed in the host configuration.
    host.xcodeVersion = xcodeVersion;
    host.appleBitcodeMode = appleBitcodeMode;

    return host;
  }
}


text:
class ApplicationController;

namespace Ui {
class AccountsWindow;
}

class AccountsWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit AccountsWindow(ApplicationController *app, QWidget *parent = nullptr);
    ~AccountsWindow();

public slots:
    void addAccount();
    //void deleteAccount();
    void removeSelectedAccount();
    void removeAccountAtIndex(const QModelIndex &index);
    void openSelectedAccount();
    void openAccountAtIndex(const QModelIndex &index);

private slots:
    void keyPressEvent(QKeyEvent *event) override;
    void on_addAccount_clicked();
    void on_removeAccount_clicked();
    void on_close_clicked();

private:
    ApplicationController *app;
    Ui::AccountsWindow *ui;
};

#endif // ACCOUNTSWINDOW_H


text:
package io.parsingdata.metal.expression.value;

import io.parsingdata.metal.data.ImmutableList;
import io.parsingdata.metal.data.ParseState;
import io.parsingdata.metal.encoding.Encoding;

/**
 * Interface for all ValueExpression implementations.
 *

 * A ValueExpression is an expression that is evaluated by executing its
 * {@link #eval(ParseState, Encoding)} method. It yields a list of
 * {@link Value} objects.
 *

 * As context, it receives the current {@link ParseState} object as
 * well as the current {@link Encoding} object.
 */
@FunctionalInterface
public interface ValueExpression {

    ImmutableList<Value> eval(ParseState parseState, Encoding encoding);

}


text:
namespace ARDUINOJSON_NAMESPACE {

namespace StringStoragePolicy {

struct Link {};
struct Copy {};
struct LinkOrCopy {
  bool link;
};
}  // namespace StringStoragePolicy

}  // namespace ARDUINOJSON_NAMESPACE


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

namespace ShoppingListService.Helpers
{
    public interface IShoppingListHelper
    {
        /// <summary>
        /// A a new item to the list
        /// </summary>
        /// <param name="list">The shopping list</param>
        /// <param name="itemName">The item to add</param>
        /// <param name="quantity">The initial quantity for the item</param>
        /// <returns>null if successful. An Error if not successful.</returns>
        RequestError Add(ShoppingList list, string itemName, int quantity);

        /// <summary>
        /// Update an item that already exists in the list
        /// </summary>
        /// <param name="list">The shopping list</param>
        /// <param name="itemName">The item to update</param>
        /// <param name="quantity">The quantity to update</param>
        /// <returns>null if successful. An Error if not successful.</returns>
        RequestError Update(ShoppingList list, string itemName, int quantity);

        /// <summary>
        /// Delete an item that exists in the list
        /// </summary>
        /// <param name="list">The shopping list</param>
        /// <param name="itemName">The item to delete</param>
        /// <returns>null if successful. An Error if not successful.</returns>
        RequestError Delete(ShoppingList list, string itemName);

        /// <summary>
        /// Get the existing list item from the list.
        /// </summary>
        /// <param name="itemName">The name of the item to get</param>
        /// <param name="list">The shopping list</param>
        /// <returns>The list item if it exists. Otherwise null.</returns>
        ShoppingListItem GetListItem(ShoppingList list, string itemName);
    }
}


text:
<?php

namespace App\Services;

use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Kevinrob\GuzzleCache\CacheMiddleware;
use webignition\Guzzle\Middleware\HttpAuthentication\HttpAuthenticationMiddleware;
use webignition\Guzzle\Middleware\RequestHeaders\RequestHeadersMiddleware;
use webignition\Guzzle\Middleware\ResponseLocationUriFixer\Factory as ResponseUriFixerFactory;
use webignition\HttpHistoryContainer\Container as HttpHistoryContainer;

class HttpHandlerStackFactory
{
    const MIDDLEWARE_CACHE_KEY = 'cache';
    const MIDDLEWARE_HTTP_AUTH_KEY = 'http-auth';
    const MIDDLEWARE_REQUEST_HEADERS_KEY = 'request-headers';
    const MIDDLEWARE_HISTORY_KEY = 'history';
    const MIDDLEWARE_RESPONSE_URL_FIXER_KEY = 'response-url-fixer';

    private $httpAuthenticationMiddleware;
    private $requestHeadersMiddleware;
    private $historyContainer;
    private $responseUriFixerFactory;
    private $cacheMiddleware;
    private $handler;

    public function __construct(
        HttpAuthenticationMiddleware $httpAuthenticationMiddleware,
        RequestHeadersMiddleware $requestHeadersMiddleware,
        HttpHistoryContainer $historyContainer,
        ResponseUriFixerFactory $responseUriFixerFactory,
        CacheMiddleware $cacheMiddleware,
        callable $handler = null
    ) {
        $this->httpAuthenticationMiddleware = $httpAuthenticationMiddleware;
        $this->requestHeadersMiddleware = $requestHeadersMiddleware;
        $this->historyContainer = $historyContainer;
        $this->responseUriFixerFactory = $responseUriFixerFactory;
        $this->cacheMiddleware = $cacheMiddleware;
        $this->handler = $handler;
    }

    public function create(): HandlerStack
    {
        $handlerStack = HandlerStack::create($this->handler);

        if ($this->cacheMiddleware) {
            $handlerStack->push($this->cacheMiddleware, self::MIDDLEWARE_CACHE_KEY);
        }

        $handlerStack->push($this->responseUriFixerFactory->create(), self::MIDDLEWARE_RESPONSE_URL_FIXER_KEY);
        $handlerStack->push($this->httpAuthenticationMiddleware, self::MIDDLEWARE_HTTP_AUTH_KEY);
        $handlerStack->push($this->requestHeadersMiddleware, self::MIDDLEWARE_REQUEST_HEADERS_KEY);
        $handlerStack->push(Middleware::history($this->historyContainer), self::MIDDLEWARE_HISTORY_KEY);

        return $handlerStack;
    }
}


text:
[![Build Status](https://travis-ci.org/customcommander/coins.js.svg?branch=master)](https://travis-ci.org/customcommander/coins.js)

# coins.js
Utility Library For COinS (ContextObjects in Spans)

### Developing

Good old `make` is used for managing the development life cycle:

0.  `make lint`

    Makes sure that all JavaScript complies with the coding standards.

0.  `make test`

    Runs tests in both environments (Node & Browser).
    It also produces a combined code coverage report.

0.  `make dist`

    Runs both `lint` and `test` targets and packages files for release.
    Changes in the `dist` directory should be checked in.


text:
package server.endpoint.client;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.xml.namespace.QName;
import jakarta.xml.ws.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.net.URL;
import java.io.*;

import testutil.PortAllocator;

/**
 * @author Jitendra Kotamraju
 */
public class R2001Test extends TestCase {

    public void testR2001() throws Exception {
        int port = PortAllocator.getFreePort();
        String address = "http://localhost:"+port+"/hello";
        Endpoint endpoint = Endpoint.create(new R2001Provider());
        List<Source> metadata = new ArrayList<Source>();
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        String[] docs = {
            "stockquoteservice.wsdl",
            "stockquote.wsdl",
            "stockquote.xsd"
        };
        for(String doc : docs) {
            URL url = cl.getResource(doc);
            metadata.add(new StreamSource(url.openStream(), url.toExternalForm()));
        }
        endpoint.setMetadata(metadata);

        Map<String, Object> props = new HashMap<String, Object>();
        props.put(Endpoint.WSDL_SERVICE, new QName("http://example.com/stockquote/service", "StockQuoteService"));
        props.put(Endpoint.WSDL_PORT, new QName("http://example.com/stockquote/service", "StockQuotePort"));
        endpoint.setProperties(props);

        endpoint.publish(address);
        URL serUrl = new URL(address+"?wsdl");
        isGenerated(serUrl.openStream());
        URL absUrl = new URL(address+"?wsdl=1");
        isGenerated(absUrl.openStream());
        URL xsdUrl = new URL(address+"?xsd=1");
        isGenerated(xsdUrl.openStream());
        endpoint.stop();
    }

    public void isGenerated(InputStream in) throws IOException {
        BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
        String str;
        while ((str=rdr.readLine()) != null);
    }

    @WebServiceProvider
    public class R2001Provider implements Provider<Source> {
        public Source invoke(Source source) {
            String replyElement = new String("
hello world
");
            StreamSource reply = new StreamSource(new StringReader (replyElement));
            return reply;
        }
    }

}


text:
using Foundation;
using Intents;
using System;
using System.Linq;
using Toggl.Core.Analytics;
using Toggl.Core.Models.Interfaces;
using Toggl.Core.UI.Navigation;
using Toggl.Core.UI.Parameters;
using Toggl.Core.UI.ViewModels;
using Toggl.iOS.Extensions;
using Toggl.iOS.Intents;
using Toggl.Shared;
using UIKit;

namespace Toggl.iOS
{
    public partial class AppDelegate
    {
        public override bool ContinueUserActivity(
            UIApplication application,
            NSUserActivity userActivity,
            UIApplicationRestorationHandler completionHandler)
        {
            var navigationService = IosDependencyContainer.Instance.NavigationService;

            var interaction = userActivity.GetInteraction();
            if (interaction == null ||
                (interaction.IntentHandlingStatus != INIntentHandlingStatus.DeferredToApplication
                && interaction.IntentHandlingStatus != INIntentHandlingStatus.Unspecified))
            {
                return false;
            }

            var intent = interaction?.Intent;

            switch (intent)
            {
                case StopTimerIntent _:
                    handleDeeplink(new Uri(ApplicationUrls.TimeEntry.Stop.FromSiri));
                    return true;
                case ShowReportIntent _:
                    handleDeeplink(new Uri(ApplicationUrls.Reports.Default));
                    return true;
                case ShowReportPeriodIntent periodIntent:
                    long? parseLong(string val) => long.TryParse(val, out var i) ? i : (long?)null;
                    long? workspaceId = parseLong(periodIntent.Workspace?.Identifier);
                    var period = periodIntent.Period.ToDateRangePeriod();
                    var viewPresenter = IosDependencyContainer.Instance.ViewPresenter;
                    var change = new ShowReportsPresentationChange(workspaceId, period);
                    viewPresenter.ChangePresentation(change);
                    return true;
                case StartTimerIntent startTimerIntent:
                    var timeEntryParams = createStartTimeEntryParameters(startTimerIntent);
                    navigationService.Navigate<MainViewModel>(null);
                    navigationService.Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(timeEntryParams, null);
                    return true;
                default:
                    return false;
            }
        }

        private StartTimeEntryParameters createStartTimeEntryParameters(StartTimerIntent intent)
        {
            var tags = (intent.Tags == null || intent.Tags.Count() == 0)
                ? null
                : intent.Tags.Select(tagid => (long)Convert.ToDouble(tagid.Identifier));

            return new StartTimeEntryParameters(
                DateTimeOffset.Now,
                "",
                null,
                string.IsNullOrEmpty(intent.Workspace?.Identifier) ? null : (long?)Convert.ToDouble(intent.Workspace?.Identifier),
                intent.EntryDescription ?? "",
                string.IsNullOrEmpty(intent.ProjectId?.Identifier) ? null : (long?)Convert.ToDouble(intent.ProjectId?.Identifier),
                string.IsNullOrEmpty(intent.TaskId?.Identifier) ? null : (long?)Convert.ToDouble(intent.TaskId?.Identifier),
                tags,
                TimeEntryStartOrigin.Siri
            );
        }
    }
}


text:
<?php

$smarty->assign("menu_item", "search");
$smarty->assign("css_link", "/css/website/list.css");
$smarty->setTitle("Search: {$_GET['q']}");

$smarty->assign("searchString", $_GET['q']);

$smarty->display("website/search.tpl");


text:
package com.goodworkalan.fossil;

import java.nio.ByteBuffer;
import java.util.Collection;

import com.goodworkalan.pack.Mutator;
import com.goodworkalan.stash.Stash;
import com.goodworkalan.strata.LeafStore;

/**
 * An implementation of an leaf tier store that writes value objects to a block
 * in a pack file.
 *
 * @author Alan Gutierrez
 *
 * @param <T>
 *            The value type of the b+tree objects.
 */
public class FossilLeafStore<T>
extends FossilStore<T>
implements LeafStore<T, Long>
{
    /**
     * Create a persistent storage strategy for leaf tier value objects with the
     * given record I/O strategy.
     *
     * @param recordIO
     *            The strategy to read and write an individual value object.
     */
    public FossilLeafStore(RecordIO<T> recordIO)
    {
        super(recordIO);
    }

    /**
     * Get the size of an leaf tier in bytes.
     *
     * @param capacity
     *            The count of value objects.
     * @return The size of the leaf tier in bytes.
     */
    protected int getByteSize(int capacity)
    {
        return Fossil.SIZEOF_INTEGER + Fossil.SIZEOF_LONG + (capacity * recordIO.getSize());
    }

    /**
     * Load a collection of value objects from the persistent storage at the
     * given address.
     *
     * @param stash
     *            A type-safe container of out of band data.
     * @param address
     *            The address of the leaf tier storage.
     * @param objects
     *            The collection to load.
     * @return The address of the next leaf in the b-tree.
     */
    public Long load(Stash stash, Long address, Collection<T> objects)
    {
        Mutator mutator = stash.get(Fossil.MUTATOR, Mutator.class);

        ByteBuffer bytes = mutator.read(address);
        int size = bytes.getInt();

        long next = bytes.getLong();

        for (int i = 0; i < size; i++)
        {
            T object = recordIO.read(bytes);
            objects.add(object);
        }

        return next;
    }

    /**
     * Write a collection of leaf tier value objects to the persistent storage
     * at the given address.
     *
     * @param stash
     *            A type-safe container of out of band data.
     * @param address
     *            The address of the leaf tier storage.
     * @param objects
     *            The collection to write.
     * @param extra
     *            Extra tier specific data.
     */
    public void write(Stash stash, Long address, Collection<T> objects, Long next)
    {
        Mutator mutator = stash.get(Fossil.MUTATOR, Mutator.class);

        ByteBuffer bytes = ByteBuffer.allocate(getByteSize(objects.size()));

        bytes.putInt(objects.size());
        bytes.putLong(next);
        for (T object : objects)
        {
            recordIO.write(bytes, object);
        }
        bytes.flip();
        mutator.write(address, bytes);
    }
}


text:
import Response from 'aws/cfnResponse'
import Cognito from 'aws/cognito'

export async function handle (event, context, callback) {
  if (event.RequestType === 'Update' || event.RequestType === 'Delete') {
    // UserPool will be deleted too, so do nothing here.
    const clientID = event.PhysicalResourceId
    await Response.sendSuccess(event, context, {UserPoolClientID: clientID}, clientID)
    return
  }

  const {
    UserPoolID: userPoolID,
    ClientName: clientName
  } = event.ResourceProperties

  try {
    const userPoolClient = await new Cognito().createUserPoolClient(userPoolID, clientName)
    const clientID = userPoolClient.ClientId
    await Response.sendSuccess(event, context, {UserPoolClientID: clientID}, clientID)
  } catch (error) {
    console.log(error.message)
    console.log(error.stack)
    await Response.sendFailed(event, context)
  }
}


text:
<?php

namespace Catalogos\Propiedad\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

//// Form ////
use Catalogos\Propiedad\Form\PropiedadForm;

//// Filter ////
use Catalogos\Propiedad\Filter\PropiedadFilter;

//// Propel ////
use Propiedad;
use PropiedadQuery;
use BasePeer;

class PropiedadController extends AbstractActionController
{
    public function nuevoAction()
    {
        $PropiedadForm = new PropiedadForm();
        $PropiedadForm->get('submit')->setValue('Nuevo');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $PropiedadFilter = new PropiedadFilter();
            $PropiedadForm->setInputFilter($PropiedadFilter->getInputFilter());
            $PropiedadForm->setData($request->getPost());

            foreach($request->getPost() as $key => $value){
                if($key == 'idarticulo'){
                    $articuloQuery = \ArticuloQuery::create()->filterByIdarticulo($value)->findOne();
                    // Validamos que exista el idarticulo.
                    if(!$articuloQuery){
                        return new ViewModel(array(
                            'Error' => array(
                                'Invalid idarticulo.' => 'Invalid idarticulo.'
                            ),
                        ));
                    }
                }
            }

            if ($PropiedadForm->isValid()) {
                $Propiedad = new Propiedad();
                foreach($PropiedadForm->getData() as $PropiedadKey => $PropiedadValue){
                    if($PropiedadKey != 'idpropiedad' && $PropiedadKey != 'submit'){
                        $Propiedad->setByName($PropiedadKey, $PropiedadValue, BasePeer::TYPE_FIELDNAME);
                    }
                }
                $Propiedad->save();
                return $this->redirect()->toRoute('propiedad');
            }else{
                $messageArray = array();
                foreach ($PropiedadForm->getMessages() as $key => $value){
                    foreach($value as $val){
                        //Obtenemos el valor de la columna con error
                        $message = $key.' '.$val;
                        array_push($messageArray, $message);
                    }
                }

                return new ViewModel(array(
                    'Error' => $messageArray,
                ));
            }
        }
        return array('PropiedadForm' => $PropiedadForm);
    }

    public function listarAction()
    {
        // Instanciamos nuestro formulario propiedadForm
        $propiedadForm = new PropiedadForm();

        // Guardamos en un arrglo los campos a los que el usuario va poder tener acceso de acuerdo a su nivel
        $allowedColumns = array();
        foreach ($propiedadForm->getElements() as $key=>$value){
            array_push($allowedColumns, $key);
        }
        //Verificamos que si nos envian filtros  si no ponemos valores por default
        $limit = (int) $this->params()->fromQuery('limit') ? (int)$this->params()->fromQuery('limit')  : 10;
        if($limit > 100) $limit = 100; //Si el limit es mayor a 100 lo establece en 100 como maximo valor permitido
        $dir = $this->params()->fromQuery('dir') ? $this->params()->fromQuery('dir')  : 'asc';
        $order = in_array($this->params()->fromQuery('order'), $allowedColumns) ? $this->params()->fromQuery('order')  : 'idpropiedad';
        $page = (int) $this->params()->fromQuery('page') ? (int)$this->params()->fromQuery('page')  : 1;

        $propiedadQuery = new PropiedadQuery();

        //Order y Dir
        if($order !=null || $dir !=null){
            $propiedadQuery->orderBy($order, $dir);
        }

        // Obtenemos el filtrado por medio del idcompany del recurso.
        $result = $propiedadQuery->paginate($page,$limit);

        $data = $result->getResults()->toArray(null,false,BasePeer::TYPE_FIELDNAME);

        return new ViewModel(array(
            'Propiedads' => $data,
        ));
    }

    public function editarAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('propiedad', array(
                'action' => 'nuevo'
            ));
        }

        //Instanciamos nuestra propiedadQuery
        $propiedadQuery = PropiedadQuery::create();

        //Verificamos que el Id propiedad que se quiere modificar exista
        if($propiedadQuery->create()->filterByIdpropiedad($id)->exists()){

            $request = $this->getRequest();
            //Instanciamos nuestra propiedadQuery
            $propiedadPKQuery = $propiedadQuery->findPk($id);
            $propiedadQueryArray = $propiedadPKQuery->toArray(BasePeer::TYPE_FIELDNAME);
            $PropiedadForm = new PropiedadForm();
            $ElementsPropiedadForm = $PropiedadForm->getElements();

            if ($request->isPost()){
                $PropiedadArray = array();
                foreach($ElementsPropiedadForm as $key=>$value){
                    if($key != 'submit'){
                        $PropiedadArray[$key] = $request->getPost()->$key ? $request->getPost()->$key : $propiedadQueryArray[$key];
                    }
                }
            }else{
                foreach($propiedadQueryArray as $propiedadQueryKey => $propiedadQueryValue){
                    $PropiedadArray[$propiedadQueryKey] = $propiedadQueryArray[$propiedadQueryKey];

                }
            }

            $PropiedadFilter = new PropiedadFilter();
            $PropiedadForm->setInputFilter($PropiedadFilter->getInputFilter());
            $PropiedadForm->setData($PropiedadArray);

            if ($PropiedadForm->isValid()) {
                foreach($PropiedadForm->getData() as $PropiedadKey => $PropiedadValue){
                    if($PropiedadKey != 'submit'){
                        $propiedadPKQuery->setByName($PropiedadKey, $PropiedadValue, BasePeer::TYPE_FIELDNAME);
                    }
                }
                // Si no modifican nada, permanecemos en el formulario.
                if($propiedadPKQuery->isModified()){
                    $propiedadPKQuery->save();
                    return $this->redirect()->toRoute('propiedad');
                }
            }else{
                $messageArray = array();
                foreach ($PropiedadForm->getMessages() as $key => $value){
                    foreach($value as $val){
                        //Obtenemos el valor de la columna con error
                        $message = $key.' '.$val;
                        array_push($messageArray, $message);
                    }
                }

                return new ViewModel(array(
                    'Error' => $messageArray,
                ));
            }
        }

        return array(
            'id' => $id,
            'PropiedadForm' => $PropiedadForm,
        );
    }

    public function eliminarAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('propiedad');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Yes') {
                $id = (int) $request->getPost('id');
                PropiedadQuery::create()->filterByIdpropiedad($id)->delete();
            }

            // Redireccionamos a los provedores
            return $this->redirect()->toRoute('propiedad');
        }

        $provedorEntity = PropiedadQuery::create()->filterByIdpropiedad($id)->findOne();
        return array(
            'id'    => $id,
            'propiedad' => $provedorEntity->toArray(BasePeer::TYPE_FIELDNAME)
        );
    }
}


text:
"use strict";

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var _expect = require("expect");

var _expect2 = _interopRequireDefault(_expect);

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _reactDom = require("react-dom");

var _reactDom2 = _interopRequireDefault(_reactDom);

var _reactAddonsTestUtils = require("react-addons-test-utils");

var _reactAddonsTestUtils2 = _interopRequireDefault(_reactAddonsTestUtils);

var _index = require("../index");

describe("ToastContainer", function () {
  describe("when component function is triggered", function () {
    describe("renders a toast message", function () {
      it("exists in the container", function () {
        var ref = _reactAddonsTestUtils2["default"].renderIntoDocument(_react2["default"].createElement(_index.ToastContainer, { toastMessageFactory: _react2["default"].createFactory(_index.ToastMessage.animation) }));
        var dom = _reactDom2["default"].findDOMNode(ref);
        (0, _expect2["default"])(dom.childNodes.length).toBe(0);

        ref.success("yeah,", "cool");
        (0, _expect2["default"])(dom.childNodes.length).toNotBe(0);
      });

      it("should be closed by clicking on it", function (done) {
        var ref = _reactAddonsTestUtils2["default"].renderIntoDocument(_react2["default"].createElement(_index.ToastContainer, { toastMessageFactory: _react2["default"].createFactory(_index.ToastMessage.animation) }));
        var dom = _reactDom2["default"].findDOMNode(ref);

        ref.success("yeah,", "cool");
        (0, _expect2["default"])(dom.childNodes.length).toNotBe(0);

        var toastDom = dom.childNodes[0];
        _reactAddonsTestUtils2["default"].Simulate.click(toastDom);

        setTimeout(function () {
          (0, _expect2["default"])(dom.childNodes.length).toBe(0);
          done();
        }, 500);
      });
    });

    it("renders a list of toast messages", function () {
      var ref = _reactAddonsTestUtils2["default"].renderIntoDocument(_react2["default"].createElement(_index.ToastContainer, { toastMessageFactory: _react2["default"].createFactory(_index.ToastMessage.animation) }));
      ref.success("yeah", "cool");
      ref.error("blabla", "foobar");

      var dom = _reactDom2["default"].findDOMNode(ref);
      (0, _expect2["default"])(dom.childNodes.length).toBe(2);

      var errorDom = dom.childNodes[0];
      (0, _expect2["default"])(errorDom.classList.contains("toast-error")).toBe(true);
      (0, _expect2["default"])(errorDom.childNodes[0].textContent).toBe("foobar");
      (0, _expect2["default"])(errorDom.childNodes[1].textContent).toBe("blabla");

      var successDom = dom.childNodes[1];
      (0, _expect2["default"])(successDom.classList.contains("toast-success")).toBe(true);
      (0, _expect2["default"])(successDom.childNodes[0].textContent).toBe("cool");
      (0, _expect2["default"])(successDom.childNodes[1].textContent).toBe("yeah");
    });
  });
});


text:
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>Detect soft navigation with replaceState.</title>

  Click me!


text:
package com.mtraina.ps {
  /**
    * In Scala you can create nested packages in the same file
    */
  package tools {
    class NumberFormatter
  }
}

object Chapter13 {
  /**
    * The import of a package can be inside the class/object definition and not only at the beginning of the file
    */
  import com.mtraina.ps.tools.NumberFormatter

  val nf: NumberFormatter = new NumberFormatter

  /**
    * By default the access modifier for Scala is public.
    * Protected and private are also allowed modifiers and they have to be explicitly used
    */
  val length = 10 // public
  protected val height = 20 // protected
  private val weight = 30   // private
}


text:
var express = require('express');
var router = express.Router();

// 以下三项是跟模型相关的自定义参数
var dbName 				= "fshop";					// 数据库名称
var modelName 			= 'models';				// 模型英文名称
var modelStr 			= '书';					// 模型中文名称

var listDataUrl = '/' + modelName + '/listData';
var addObjectPageName = '添加' + modelStr;
var updateObjectPageName = '修改' + modelStr;
var formUrl = '/' + modelName + '/update';

var mongojs =require('mongojs');	// mongojs 访问数据库
var collectionName = modelName;
var db = require('mongojs').connect(dbName,[modelName]);

var _ = require('underscore');

router.get(	'/list', list );
router.get(	'/listData', listData );
router.get(	'/info/:id', info );
router.get(	'/update/:id', update );
router.post('/updateAction', updateAction );
router.get(	'/add', add );
router.post('/addAction', addAction );
router.get(	'/del/:id', del );

// router.get('/madd', madd);

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fshop');
var Schema = mongoose.Schema;

var objSchema = new Schema({
	title:  String,
	author: String,
	body:   String,
	hidden: Boolean,
});
var objModel = mongoose.model('book', objSchema);

function _infoJump(res, info, targetUrl){
	rend = { msg : info, targetUrl : targetUrl };
	res.render("./public/info.html", rend);
}

// same
function list(req, res){
	var rend = {
					modelStr : modelStr,
					modelName: modelName,
					listDataUrl  : listDataUrl
				}
	res.render("./" + modelName + "/list.html", rend );
}

function listData(req, res){
	objModel.find({}, function(err, records){
		res.set('Access-Control-Allow-Origin', '*');		// 让来自于APP和网页的程序可以跨域访问
		res.json({data: records});
	});
}

function add(req, res){
	formUrl = '/' + modelName + '/addAction';
	var rend = {
					modelStr : modelStr,
					modelName: modelName,
					pageName : addObjectPageName,
					formUrl  : formUrl,
					msg      : "无",
				}
	res.render("./" + modelName + "/update.html", rend );
}

function addAction(req, res){
	updateInfo =  req.body;
	updateInfo = _.omit(req.body, '_id');
	var obj = new objModel(updateInfo);
	obj.save(function(err,saveRes){
		if (err) {
			console.log(' ERROR: 	' + modelName + '.js 	addAction.   Message : ');	console.dir(err);
			_infoJump(res, '添加' + modelStr + '失败,即将跳转回首页' , '/');
		} else{
			_infoJump(res, '添加' + modelStr + '成功,即将跳转回首页' , '/');
		};
	});
}

function update(req, res){
	formUrl = '/' + modelName + '/updateAction';
	var rend = {
					modelStr : modelStr,
					modelName: modelName,
					pageName : updateObjectPageName,
					formUrl  : formUrl,
					msg      : "无",
				}
	res.render("./" + modelName + "/update.html", rend );
}

function info(req, res){
	objectId = req.params.id;
	// console.log(modelName + ' 	info 		objectId = ' + objectId );
	// 把指定对象的信息找回来
	objModel.findById(objectId).exec(function(err, thing){
		res.json(thing);
	});
}

function updateAction(req, res){
	var objectId = req.param('_id');
	// console.log(modelName + ' 	updateAction 		objectId = ' + objectId );
	var updateInfo =  req.body;
	var updateInfo = _.omit(req.body, '_id');
	var cond = {_id: objectId};
	objModel.update(cond, updateInfo, function(err, result){
		if (err) {
			console.log(' ERROR: 	' + modelName + '.js 	addAction.   Message : ');
			console.dir(err);
			_infoJump(res, '修改' + modelStr + '失败,即将跳转回首页' , '/');
		};
		_infoJump(res, '修改' + modelStr + '成功,即将跳转回首页' , '/');
	});
}

function del(req, res){
	objectId = req.params.id;
	// console.log(modelName + ' 	del 		objectId = ' + objectId );
	var cond = { _id : objectId };
	objModel.remove(cond, function(err, result){
		if (err) {
			console.log(' ERROR: 	' + modelName + '.js 	del Action.   Message : ');
			console.dir(err);
			_infoJump(res, '删除' + modelStr + '失败,即将跳转回首页' , '/');
		};
		_infoJump(res, '删除' + modelStr + '成功,即将跳转回首页' , '/');
	});
}

module.exports = router;


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>Wyatt-STM: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Wyatt-STM
    1.0.0

Software transactional memory system developed at Wyatt Technology

Main Page

Modules

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

WSTM

WExceptionCapture

WSTM::WExceptionCapture Member List

This is the complete list of members for WSTM::WExceptionCapture, including all inherited members.

Capture(const WExceptionCapture &exc)	WSTM::WExceptionCapture

Capture(const WExceptionCapture &exc, WAtomic &at)	WSTM::WExceptionCapture

Capture(const Capture_t &exc)	WSTM::WExceptionCapture	inline

Capture(const Capture_t &exc, WAtomic &at)	WSTM::WExceptionCapture	inline

HasCaptured(WAtomic &at) const 	WSTM::WExceptionCapture

operator bool() const 	WSTM::WExceptionCapture

operator=(const WExceptionCapture &exc)	WSTM::WExceptionCapture

operator=(WExceptionCapture &&exc)	WSTM::WExceptionCapture

Reset()	WSTM::WExceptionCapture

Reset(WAtomic &at)	WSTM::WExceptionCapture

ThrowCaptured() const 	WSTM::WExceptionCapture

ThrowCaptured(WAtomic &at) const 	WSTM::WExceptionCapture

WExceptionCapture()	WSTM::WExceptionCapture

WExceptionCapture(const Capture_t &exc)	WSTM::WExceptionCapture	inline

WExceptionCapture(const Capture_t &exc, WAtomic &at)	WSTM::WExceptionCapture	inline

WExceptionCapture(const WExceptionCapture &exc)	WSTM::WExceptionCapture

WExceptionCapture(WExceptionCapture &&exc)	WSTM::WExceptionCapture

<address class="footer">
Generated by

 1.8.10
</address>


text:
extern const char http_http[8];
extern const char http_200[5];
extern const char http_301[5];
extern const char http_302[5];
extern const char http_get[5];
extern const char http_10[9];
extern const char http_11[9];
extern const char http_content_type[15];
extern const char http_texthtml[10];
extern const char http_location[11];
extern const char http_host[7];
extern const char http_crnl[3];
extern const char http_index_html[12];
extern const char http_404_html[10];
extern const char http_referer[9];
extern const char http_header_200[84];
extern const char http_header_404[91];
extern const char http_content_type_plain[29];
extern const char http_content_type_html[28];
extern const char http_content_type_css [27];
extern const char http_content_type_text[28];
extern const char http_content_type_png [28];
extern const char http_content_type_gif [28];
extern const char http_content_type_jpg [29];
extern const char http_content_type_binary[43];
extern const char http_html[6];
extern const char http_shtml[7];
extern const char http_htm[5];
extern const char http_css[5];
extern const char http_png[5];
extern const char http_gif[5];
extern const char http_jpg[5];
extern const char http_text[5];
extern const char http_txt[5];


text:
#ifndef WebGLContextGroup_h
#define WebGLContextGroup_h

#include "core/html/canvas/WebGLRenderingContext.h"
#include <wtf/HashSet.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>

namespace WebCore {

class GraphicsContext3D;
class WebGLExtension;
class WebGLSharedObject;
class WebGLRenderingContext;

typedef int ExceptionCode;

class WebGLContextGroup : public RefCounted<WebGLContextGroup> {
public:
    static PassRefPtr<WebGLContextGroup> create();
    virtual ~WebGLContextGroup();

    void addContext(WebGLRenderingContext*);
    void removeContext(WebGLRenderingContext*);

    void addObject(WebGLSharedObject*);
    void removeObject(WebGLSharedObject*);

    GraphicsContext3D* getAGraphicsContext3D();

    void loseContextGroup(WebGLRenderingContext::LostContextMode);

  private:
    friend class WebGLObject;

    WebGLContextGroup();

    void detachAndRemoveAllObjects();

    HashSet<WebGLRenderingContext*> m_contexts;
    HashSet<WebGLSharedObject*> m_groupObjects;
};

} // namespace WebCore

#endif // WebGLContextGroup_h


text:
package de.tudarmstadt.ukp.experiments.argumentation.sequence.report;

import de.tudarmstadt.ukp.dkpro.argumentation.preprocessing.annotation.ArgumentBIOAnnotator;
import de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.ConfusionMatrix;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author Ivan Habernal
 */
public class ReportTools
{
    /**
     * Returns a list of  {@code size} elements and if the {@code goldLabelSentenceLevel} is B-XX
     * tag, returns [B-XX, I-XX, I-XX, ...], otherwise [I-XX, I-XX, I-XX, ..]
     *
     * @param goldLabelSentenceLevel gold label for sentence
     * @param size                   length of sentence
     * @return list
     */
    public static List<String> recreateTokenLabels(String goldLabelSentenceLevel, int size)
    {
        List<String> result = new ArrayList<>();
        result.add(goldLabelSentenceLevel);

        for (int i = 1; i < size; i++) {

            if (goldLabelSentenceLevel.endsWith(ArgumentBIOAnnotator.B_SUFFIX)) {
                result.add(goldLabelSentenceLevel
                        .replace(ArgumentBIOAnnotator.B_SUFFIX, ArgumentBIOAnnotator.I_SUFFIX));
            }
            else {
                result.add(goldLabelSentenceLevel);
            }
        }

        //        System.out.println(goldLabelSentenceLevel + ": " + result);

        return result;
    }

    /**
     * Prints macro F1 and F1 for each label into file (each line: label + F1, tab delimited)
     *
     * @param confusionMatrix matrix
     * @param file            file
     * @throws IOException
     */
    public static void printFMeasuresToFile(ConfusionMatrix confusionMatrix, File file)
            throws IOException
    {
        // and write to the output
        PrintWriter pw = new PrintWriter(file);
        // print macro F1 first
        pw.printf(Locale.ENGLISH, "%s\t%.3f%n", "Macro-Fm", confusionMatrix.getMacroFMeasure());

        // then for all labels
        for (Map.Entry<String, Double> entry : confusionMatrix.getFMeasureForLabels().entrySet()) {
            pw.printf(Locale.ENGLISH, "%s\t%.3f%n", entry.getKey(), entry.getValue());
        }
        IOUtils.closeQuietly(pw);
    }
}


text:
function lemonFileBrowser(field_name, url, type, win) {
  tinyMCE.activeEditor.windowManager.open({
    'file': "{{ url }}?pop=1&editor=tinymce&type=" + type,
    'width': 820,
    'height': 500,
    'resizable': "yes",
    'scrollbars': "yes",
    'inline': "no",
    'close_previous': "no",
    'popup_css': false
  }, {
    'window': win,
    'input': field_name,
    'editor_id': tinyMCE.selectedInstance.editorId
  });
  return false;
}