text:
#include "modules/localization/ndt/ndt_locator/lidar_locator_ndt.h"

#include <iostream>
#include <sstream>

#include <boost/filesystem.hpp>
#include "gtest/gtest.h"
#include "pcl/io/pcd_io.h"

#include "cyber/common/log.h"
#include "modules/localization/msf/common/io/pcl_point_types.h"
#include "modules/localization/msf/common/io/velodyne_utility.h"

namespace apollo {
namespace localization {
namespace ndt {

TEST(LidarLocatorNdtTestSuite, LidarLocatorNdt) {
  const std::string map_folder =
      "/apollo/modules/localization/ndt/test_data/ndt_map";
  const std::string poses_file =
      "/apollo/modules/localization/ndt/test_data/pcds/poses.txt";
  LidarLocatorNdt locator;

  // Locator settings.
  locator.SetMapFolderPath(map_folder);
  Eigen::Affine3d velodyne_extrinsic(Eigen::Matrix4d::Identity());
  locator.SetVelodyneExtrinsic(velodyne_extrinsic);
  locator.SetOnlineCloudResolution(1.0);
  locator.SetLidarHeight(1.7);

  // Load poses.
  std::vector<Eigen::Affine3d, Eigen::aligned_allocator<Eigen::Affine3d>> poses;
  std::vector<double> timestamps;
  msf::velodyne::LoadPcdPoses(poses_file, &poses, &timestamps);
  Eigen::Affine3d location = Eigen::Affine3d::Identity();

  unsigned int frame_idx = 0;
  for (; frame_idx < poses.size(); ++frame_idx) {
    // Config.
    const unsigned int resolution_id = 0;
    const int zone_id = 10;
    if (!locator.IsInitialized()) {
      locator.Init(poses[frame_idx], resolution_id, zone_id);
      continue;
    }

    ::apollo::common::EigenVector3dVec pt3ds;
    std::vector<unsigned char> intensities;
    std::stringstream ss;
    ss << frame_idx + 1;
    std::string pcd_file_path =
        "/apollo/modules/localization/ndt/test_data/pcds/" + ss.str() + ".pcd";
    msf::velodyne::LoadPcds(pcd_file_path, frame_idx, poses[frame_idx], &pt3ds,
                            &intensities);
    LidarFrame lidar_frame;
    lidar_frame.measurement_time = timestamps[frame_idx];
    lidar_frame.pt_xs.reserve(pt3ds.size());
    lidar_frame.pt_ys.reserve(pt3ds.size());
    lidar_frame.pt_zs.reserve(pt3ds.size());
    lidar_frame.intensities.reserve(pt3ds.size());
    for (unsigned int i = 0; i < pt3ds.size(); ++i) {
      lidar_frame.pt_xs.push_back(static_cast<float>(pt3ds[i][0]));
      lidar_frame.pt_ys.push_back(static_cast<float>(pt3ds[i][1]));
      lidar_frame.pt_zs.push_back(static_cast<float>(pt3ds[i][2]));
      lidar_frame.intensities.push_back(intensities[i]);
    }
    int ret = locator.Update(0, poses[frame_idx], lidar_frame);
    EXPECT_LE(std::fabs(ret - 0), 1e-6);

    location = locator.GetPose();
  }
  EXPECT_LE(std::fabs(location.translation()[0] - 588349.337377345), 0.1);
  EXPECT_LE(std::fabs(location.translation()[1] - 4141239.53859664), 0.1);
  EXPECT_LE(std::fabs(location.translation()[2] + 30.0964486966756), 0.1);
  EXPECT_EQ(frame_idx, 2);
}

}  // namespace ndt
}  // namespace localization
}  // namespace apollo


text:
page_title: Troubleshooting
page_description: Troubleshooting
page_keywords: grafana, support, documentation

# Troubleshooting

This page is dedicated to helping you solve any problem you have getting Grafana to work. Please review it before
opening a new github issue or asking a question in #grafana on freenode.

## General connection issues
When setting up Grafana for the first time you might experiance issues with Grafana being unable to query Graphite, OpenTSDB or InfluxDB.
You might not be able to get metric name completion or the graph might show an error like this:

![](/img/v1/graph_timestore_error.png)

For some type of errors the ``View details`` link will show you error details. But for many types of HTTP connection errors there is
very little information. The best way to troubleshoot these issues is use
[Chrome developer tools](https://developer.chrome.com/devtools/index). By pressing F12 you can bring up the chrome dev tools.

![](/img/v1/toubleshooting_chrome_dev_tools.png)

There are two important tabs in the chrome dev tools, ``Network`` and ``Console``. Console will show you javascript errors and HTTP
request errors. In the Network tab you will be able to identifiy the request that failed and review request and response parameters.
This information will be of great help in finding the cause of the error. If you are unable to solve the issue, even after reading
the remainder of this troubleshooting guide, you may open a [github support issue](https://github.com/grafana/grafana/issues).
Before you do that please search the existing closed or open issues. Also if you need to create a support issue,
screenshots and or text information about the chrome console error, request and response information from the network tab in chrome
developer tools are of great help.

### Inspecting Grafana metric requests
![](/img/v1/toubleshooting_chrome_dev_tools_network.png)

After open chrome developer tools for the first time the Network tab is empty you need to refresh the page to get requests to show.
For some type of errors (CORS related) there might not be a response at all.

## Graphite connection issues
If your Graphite web server is on another domain or IP than your Grafana web server you will need to [setup
CORS](../install/#graphite-server-config) (Cross Origin Resource Sharing).

You know if you are having CORS related issues if you get an error like this in chrome developer tools:

![](/img/v1/toubleshooting_graphite_cors_error.png)

If the request failed on method ``OPTIONS`` then you need to review your graphite web server configuration.

## Only blank white page
When you load Grafana and all you get is a blank white page then you probably have a javascript syntax error in ``config.js``.
In chrome developer tools console you will quickly identify the line of the syntax error.

redpajama_set_name: RedPajamaGithub


text:
"""
A module for automatically creating simple proof files from
WOFF files. *proofFont* is the only public function.

This can also be used as a command line tool for generating
proofs from WOFF files.
"""

# import test

importErrors = []
try:
    import numpy
except:
    importErrors.append("numpy")
try:
    import fontTools
except ImportError:
    importErrors.append("fontTools")
try:
    import woffTools
except ImportError:
    importErrors.append("woffTools")

if importErrors:
    import sys
    print("Could not import needed module(s): %s" % ", ".join(importErrors))
    sys.exit()

# import

import os
import optparse
import unicodedata
from woffTools import WOFFFont
from woffTools.tools.css import makeFontFaceRule, makeFontFaceFontFamily
from woffTools.tools.support import startHTML, finishHTML, findUniqueFileName

# ----------------
# Report Functions
# ----------------

def writeFileInfo(font, fontPath, writer):
    # start the block
    writer.begintag("div", c_l_a_s_s="infoBlock")
    # title
    writer.begintag("h3", c_l_a_s_s="infoBlockTitle")
    writer.write("File Information")
    writer.endtag("h3")
    # table
    writer.begintag("table", c_l_a_s_s="report")
    writeFileInfoRow("FILE", os.path.basename(fontPath), writer)
    writeFileInfoRow("DIRECTORY", os.path.dirname(fontPath), writer)
    writeFileInfoRow("VERSION", "%d.%d" % (font.majorVersion, font.minorVersion), writer)
    writer.endtag("table")
    # close the container
    writer.endtag("div")

def writeFileInfoRow(title, value, writer):
    # row
    writer.begintag("tr")
    # title
    writer.begintag("td", c_l_a_s_s="title")
    writer.write(title)
    writer.endtag("td")
    # message
    writer.begintag("td")
    writer.write(value)
    writer.endtag("td")
    # close row
    writer.endtag("tr")

def writeCharacterSet(font, writer, pointSizes=[9, 10, 11, 12, 14, 18, 24, 36, 48, 72], sampleText=None):
    characterSet = makeCharacterSet(font)
    for size in pointSizes:
        # start the block
        writer.begintag("div", c_l_a_s_s="infoBlock")
        # title
        writer.begintag("h4", c_l_a_s_s="infoBlockTitle")
        writer.write("%dpx" % size)
        writer.endtag("h4")
        # character set
        writer.begintag("p", style="font-size: %dpx;" % size, c_l_a_s_s="characterSet")
        writer.write(characterSet)
        writer.endtag("p")
        # sample text
        if sampleText:
            writer.begintag("p", style="font-size: %dpx;" % size, c_l_a_s_s="sampleText")
            writer.write(sampleText)
            writer.endtag("p")
        # close the container
        writer.endtag("div")

# -------------
# Character Set
# -------------

def makeCharacterSet(font):
    cmap = font["cmap"]
    table = cmap.getcmap(3, 1)
    mapping = table.cmap
    categorizedCharacters = {}
    glyphNameToCharacter = {}
    for value, glyphName in sorted(mapping.items()):
        character = unichr(value)
        # skip whitespace
        if not character.strip():
            continue
        if glyphName not in glyphNameToCharacter:
            glyphNameToCharacter[glyphName] = []
        glyphNameToCharacter[glyphName].append(character)
    # use the glyph order defined in the font
    sortedCharacters = []
    for glyphName in font.getGlyphOrder():
        if glyphName in glyphNameToCharacter:
            sortedCharacters += glyphNameToCharacter[glyphName]
    return u"".join(sortedCharacters)

# ---------------
# Public Function
# ---------------

def proofFont(font, fontPath, sampleText=None):
    """
    Create a proof file from the given font. This always
    returns HTML.

    Arguments:
    **font** - A *WOFFFont* object from *woffLib*.
    **fontPath** - The location of the font file. At the least, this should be the file name for the font.
    **sampleText** - A string of text to display. If not provided, no text will be displayed.
    """
    # start the html
    title = "Proof: %s" % os.path.basename(fontPath)
    cssReplacements = {
        "/* proof: @font-face rule */" : makeFontFaceRule(font, fontPath, doLocalSrc=False),
        "/* proof: @font-face font-family */" : makeFontFaceFontFamily(font)
    }
    writer = startHTML(title=title, cssReplacements=cssReplacements)
    # file info
    writeFileInfo(font, fontPath, writer)
    # character set
    writeCharacterSet(font, writer, sampleText=sampleText)
    # finish the html
    text = finishHTML(writer)
    text = text.replace("%%break%%", "</br>")
    # return
    return text

# --------------------
# Command Line Behvior
# --------------------

usage = "%prog [options] fontpath1 fontpath2"

description = """This tool displays information about the
contents of one or more WOFF files.
"""

defaultSampleText = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. The quick brown fox jumps over the lazy dog."

def main():
    parser = optparse.OptionParser(usage=usage, description=description, version="%prog 0.1beta")
    parser.add_option("-d", dest="outputDirectory", help="Output directory. The default is to output the proof into the same directory as the font file.")
    parser.add_option("-o", dest="outputFileName", help="Output file name. The default is \"fontfilename_proof.html\".")
    parser.add_option("-t", dest="sampleTextFile", help="Sample text file. A file containing sample text to display. If not file is provided, The quick brown fox... will be used.")
    parser.set_defaults(excludeTests=[])
    (options, args) = parser.parse_args()
    outputDirectory = options.outputDirectory
    if outputDirectory is not None and not os.path.exists(outputDirectory):
        print("Directory does not exist:", outputDirectory)
        sys.exit()
    sampleText = defaultSampleText
    if options.sampleTextFile:
        if not os.path.exists(options.sampleTextFile):
            print("Sample text file does not exist: %s" % options.sampleTextFile)
            sys.exit()
        f = open(options.sampleTextFile, "r")
        sampleText = f.read()
        f.close()
    for fontPath in args:
        if not os.path.exists(fontPath):
            print("File does not exist: %s" % fontPath)
            sys.exit()
        else:
            print("Creating Proof: %s..." % fontPath)
            fontPath = fontPath.decode("utf-8")
            font = WOFFFont(fontPath)
            html = proofFont(font, fontPath, sampleText=sampleText)
            # make the output file name
            if options.outputFileName is not None:
                fileName = options.outputFileName
            else:
                fileName = os.path.splitext(os.path.basename(fontPath))[0]
                fileName += "_proof.html"
            # make the output directory
            if options.outputDirectory is not None:
                directory = options.outputDirectory
            else:
                directory = os.path.dirname(fontPath)
            # write the file
            path = os.path.join(directory, fileName)
            path = findUniqueFileName(path)
            f = open(path, "wb")
            f.write(html)
            f.close()

if __name__ == "__main__":
    main()


text:
"""Support for Xiaomi Yeelight WiFi color bulb."""

from datetime import timedelta
import logging

import voluptuous as vol
from yeelight import Bulb, BulbException

from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.discovery import SERVICE_YEELIGHT
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.const import (
    ATTR_ENTITY_ID,
    CONF_DEVICES,
    CONF_HOST,
    CONF_NAME,
    CONF_SCAN_INTERVAL,
)
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.dispatcher import dispatcher_connect, dispatcher_send
from homeassistant.helpers.event import track_time_interval

_LOGGER = logging.getLogger(__name__)

DOMAIN = "yeelight"
DATA_YEELIGHT = DOMAIN
DATA_UPDATED = "yeelight_{}_data_updated"
DEVICE_INITIALIZED = f"{DOMAIN}_device_initialized"

DEFAULT_NAME = "Yeelight"
DEFAULT_TRANSITION = 350

CONF_MODEL = "model"
CONF_TRANSITION = "transition"
CONF_SAVE_ON_CHANGE = "save_on_change"
CONF_MODE_MUSIC = "use_music_mode"
CONF_FLOW_PARAMS = "flow_params"
CONF_CUSTOM_EFFECTS = "custom_effects"
CONF_NIGHTLIGHT_SWITCH_TYPE = "nightlight_switch_type"

ATTR_COUNT = "count"
ATTR_ACTION = "action"
ATTR_TRANSITIONS = "transitions"

ACTION_RECOVER = "recover"
ACTION_STAY = "stay"
ACTION_OFF = "off"

ACTIVE_MODE_NIGHTLIGHT = "1"
ACTIVE_COLOR_FLOWING = "1"

NIGHTLIGHT_SWITCH_TYPE_LIGHT = "light"

SCAN_INTERVAL = timedelta(seconds=30)

YEELIGHT_RGB_TRANSITION = "RGBTransition"
YEELIGHT_HSV_TRANSACTION = "HSVTransition"
YEELIGHT_TEMPERATURE_TRANSACTION = "TemperatureTransition"
YEELIGHT_SLEEP_TRANSACTION = "SleepTransition"

YEELIGHT_FLOW_TRANSITION_SCHEMA = {
    vol.Optional(ATTR_COUNT, default=0): cv.positive_int,
    vol.Optional(ATTR_ACTION, default=ACTION_RECOVER): vol.Any(
        ACTION_RECOVER, ACTION_OFF, ACTION_STAY
    ),
    vol.Required(ATTR_TRANSITIONS): [
        {
            vol.Exclusive(YEELIGHT_RGB_TRANSITION, CONF_TRANSITION): vol.All(
                cv.ensure_list, [cv.positive_int]
            ),
            vol.Exclusive(YEELIGHT_HSV_TRANSACTION, CONF_TRANSITION): vol.All(
                cv.ensure_list, [cv.positive_int]
            ),
            vol.Exclusive(YEELIGHT_TEMPERATURE_TRANSACTION, CONF_TRANSITION): vol.All(
                cv.ensure_list, [cv.positive_int]
            ),
            vol.Exclusive(YEELIGHT_SLEEP_TRANSACTION, CONF_TRANSITION): vol.All(
                cv.ensure_list, [cv.positive_int]
            ),
        }
    ],
}

DEVICE_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_TRANSITION, default=DEFAULT_TRANSITION): cv.positive_int,
        vol.Optional(CONF_MODE_MUSIC, default=False): cv.boolean,
        vol.Optional(CONF_SAVE_ON_CHANGE, default=False): cv.boolean,
        vol.Optional(CONF_NIGHTLIGHT_SWITCH_TYPE): vol.Any(
            NIGHTLIGHT_SWITCH_TYPE_LIGHT
        ),
        vol.Optional(CONF_MODEL): cv.string,
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA},
                vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
                vol.Optional(CONF_CUSTOM_EFFECTS): [
                    {
                        vol.Required(CONF_NAME): cv.string,
                        vol.Required(CONF_FLOW_PARAMS): YEELIGHT_FLOW_TRANSITION_SCHEMA,
                    }
                ],
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

YEELIGHT_SERVICE_SCHEMA = vol.Schema({vol.Required(ATTR_ENTITY_ID): cv.entity_ids})

UPDATE_REQUEST_PROPERTIES = [
    "power",
    "main_power",
    "bright",
    "ct",
    "rgb",
    "hue",
    "sat",
    "color_mode",
    "flowing",
    "bg_power",
    "bg_lmode",
    "bg_flowing",
    "bg_ct",
    "bg_bright",
    "bg_hue",
    "bg_sat",
    "bg_rgb",
    "nl_br",
    "active_mode",
]

def setup(hass, config):
    """Set up the Yeelight bulbs."""
    conf = config.get(DOMAIN, {})
    yeelight_data = hass.data[DATA_YEELIGHT] = {}

    def device_discovered(_, info):
        _LOGGER.debug("Adding autodetected %s", info["hostname"])

        name = "yeelight_%s_%s" % (info["device_type"], info["properties"]["mac"])

        device_config = DEVICE_SCHEMA({CONF_NAME: name})

        _setup_device(hass, config, info[CONF_HOST], device_config)

    discovery.listen(hass, SERVICE_YEELIGHT, device_discovered)

    def update(_):
        for device in list(yeelight_data.values()):
            device.update()

    track_time_interval(hass, update, conf.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL))

    def load_platforms(ipaddr):
        platform_config = hass.data[DATA_YEELIGHT][ipaddr].config.copy()
        platform_config[CONF_HOST] = ipaddr
        platform_config[CONF_CUSTOM_EFFECTS] = config.get(DOMAIN, {}).get(
            CONF_CUSTOM_EFFECTS, {}
        )
        load_platform(hass, LIGHT_DOMAIN, DOMAIN, platform_config, config)
        load_platform(hass, BINARY_SENSOR_DOMAIN, DOMAIN, platform_config, config)

    dispatcher_connect(hass, DEVICE_INITIALIZED, load_platforms)

    if DOMAIN in config:
        for ipaddr, device_config in conf[CONF_DEVICES].items():
            _LOGGER.debug("Adding configured %s", device_config[CONF_NAME])
            _setup_device(hass, config, ipaddr, device_config)

    return True

def _setup_device(hass, _, ipaddr, device_config):
    devices = hass.data[DATA_YEELIGHT]

    if ipaddr in devices:
        return

    device = YeelightDevice(hass, ipaddr, device_config)

    devices[ipaddr] = device
    hass.add_job(device.setup)

class YeelightDevice:
    """Represents single Yeelight device."""

    def __init__(self, hass, ipaddr, config):
        """Initialize device."""
        self._hass = hass
        self._config = config
        self._ipaddr = ipaddr
        self._name = config.get(CONF_NAME)
        self._model = config.get(CONF_MODEL)
        self._bulb_device = Bulb(self.ipaddr, model=self._model)
        self._device_type = None
        self._available = False
        self._initialized = False

    @property
    def bulb(self):
        """Return bulb device."""
        return self._bulb_device

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def config(self):
        """Return device config."""
        return self._config

    @property
    def ipaddr(self):
        """Return ip address."""
        return self._ipaddr

    @property
    def available(self):
        """Return true is device is available."""
        return self._available

    @property
    def model(self):
        """Return configured device model."""
        return self._model

    @property
    def is_nightlight_supported(self) -> bool:
        """Return true / false if nightlight is supported."""
        if self.model:
            return self.bulb.get_model_specs().get("night_light", False)

        # It should support both ceiling and other lights
        return self._nightlight_brightness is not None

    @property
    def is_nightlight_enabled(self) -> bool:
        """Return true / false if nightlight is currently enabled."""
        if self.bulb is None:
            return False

        # Only ceiling lights have active_mode, from SDK docs:
        # active_mode 0: daylight mode / 1: moonlight mode (ceiling light only)
        if self._active_mode is not None:
            return self._active_mode == ACTIVE_MODE_NIGHTLIGHT

        if self._nightlight_brightness is not None:
            return int(self._nightlight_brightness) > 0

        return False

    @property
    def is_color_flow_enabled(self) -> bool:
        """Return true / false if color flow is currently running."""
        return self._color_flow == ACTIVE_COLOR_FLOWING

    @property
    def _active_mode(self):
        return self.bulb.last_properties.get("active_mode")

    @property
    def _color_flow(self):
        return self.bulb.last_properties.get("flowing")

    @property
    def _nightlight_brightness(self):
        return self.bulb.last_properties.get("nl_br")

    @property
    def type(self):
        """Return bulb type."""
        if not self._device_type:
            self._device_type = self.bulb.bulb_type

        return self._device_type

    def turn_on(self, duration=DEFAULT_TRANSITION, light_type=None, power_mode=None):
        """Turn on device."""
        try:
            self.bulb.turn_on(
                duration=duration, light_type=light_type, power_mode=power_mode
            )
        except BulbException as ex:
            _LOGGER.error("Unable to turn the bulb on: %s", ex)

    def turn_off(self, duration=DEFAULT_TRANSITION, light_type=None):
        """Turn off device."""
        try:
            self.bulb.turn_off(duration=duration, light_type=light_type)
        except BulbException as ex:
            _LOGGER.error(
                "Unable to turn the bulb off: %s, %s: %s", self.ipaddr, self.name, ex
            )

    def _update_properties(self):
        """Read new properties from the device."""
        if not self.bulb:
            return

        try:
            self.bulb.get_properties(UPDATE_REQUEST_PROPERTIES)
            self._available = True
            if not self._initialized:
                self._initialize_device()
        except BulbException as ex:
            if self._available:  # just inform once
                _LOGGER.error(
                    "Unable to update device %s, %s: %s", self.ipaddr, self.name, ex
                )
            self._available = False

        return self._available

    def _initialize_device(self):
        self._initialized = True
        dispatcher_send(self._hass, DEVICE_INITIALIZED, self.ipaddr)

    def update(self):
        """Update device properties and send data updated signal."""
        self._update_properties()
        dispatcher_send(self._hass, DATA_UPDATED.format(self._ipaddr))

    def setup(self):
        """Fetch initial device properties."""
        initial_update = self._update_properties()

        # We can build correct class anyway.
        if not initial_update and self.model:
            self._initialize_device()


text:
package org.batfish.question.evpnl3vniproperties;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.questions.Question;

/** A question that returns a table with VXLAN network segments and their properties. */
@ParametersAreNonnullByDefault
public final class EvpnL3VniPropertiesQuestion extends Question {
  private static final String PROP_NODES = "nodes";

  @Nullable private String _nodes;

  @Override
  public boolean getDataPlane() {
    return false;
  }

  @Override
  public String getName() {
    return "evpnL3VniProperties";
  }

  @JsonCreator
  private static @Nonnull EvpnL3VniPropertiesQuestion create(
      @Nullable @JsonProperty(PROP_NODES) String nodes) {
    return new EvpnL3VniPropertiesQuestion(nodes);
  }

  public EvpnL3VniPropertiesQuestion(@Nullable String nodes) {
    _nodes = nodes;
  }

  @JsonProperty(PROP_NODES)
  public @Nullable String getNodes() {
    return _nodes;
  }

  @Override
  public boolean equals(@Nullable Object o) {
    if (!(o instanceof EvpnL3VniPropertiesQuestion)) {
      return false;
    }
    EvpnL3VniPropertiesQuestion that = (EvpnL3VniPropertiesQuestion) o;
    return Objects.equals(_nodes, that._nodes);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(_nodes);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Municipio" table="municipio">
    <id name="id" type="integer" column="id">
      <generator strategy="SEQUENCE"/>
    </id>
    <field name="nombremunicipio" type="string" column="nombremunicipio" length="50" nullable="false"/>
    <many-to-one field="iddepartamento" target-entity="Departamento">
      <join-columns>
        <join-column name="iddepartamento" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
namespace Lucene.Net.Util.Fst
{

    using DataInput = Lucene.Net.Store.DataInput;
    using DataOutput = Lucene.Net.Store.DataOutput;

    ///
    /// Represents the outputs for an FST, providing the basic
    /// algebra required for building and traversing the FST.
    ///
    ///
Note that any operation that returns NO_OUTPUT must
    /// return the same singleton object from {@link
    /// #getNoOutput}.

    ///
    /// @lucene.experimental
    ///

    public abstract class Outputs<T>
    {
        // TODO: maybe change this API to allow for re-use of the
        // output instances -- this is an insane amount of garbage
        // (new object per byte/char/int) if eg used during
        // analysis

        ///
        /// Eg common("foobar", "food") -> "foo"
        public abstract T Common(T output1, T output2);

        ///
        /// Eg subtract("foobar", "foo") -> "bar"
        public abstract T Subtract(T output, T inc);

        ///
        /// Eg add("foo", "bar") -> "foobar"
        public abstract T Add(T prefix, T output);

        ///
        /// Encode an output value into a <seealso cref="DataOutput"/>.
        public abstract void Write(T output, DataOutput @out);

        ///
        /// Encode an final node output value into a {@link
        ///  DataOutput}.  By default this just calls {@link #write(Object,
        ///  DataOutput)}.
        ///
        public virtual void WriteFinalOutput(T output, DataOutput @out)
        {
            Write(output, @out);
        }

        ///
        /// Decode an output value previously written with {@link
        ///  #write(Object, DataOutput)}.
        ///
        public abstract T Read(DataInput @in);

        ///
        /// Decode an output value previously written with {@link
        ///  #writeFinalOutput(Object, DataOutput)}.  By default this
        ///  just calls <seealso cref="#read(DataInput)"/>.
        ///
        public virtual T ReadFinalOutput(DataInput @in)
        {
            return Read(@in);
        }

        ///
        /// NOTE: this output is compared with == so you must
        ///  ensure that all methods return the single object if
        ///  it's really no output
        ///
        public abstract T NoOutput { get; }

        public abstract string OutputToString(T output);

        // TODO: maybe make valid(T output) public...?  for asserts

        public virtual T Merge(T first, T second)
        {
            throw new System.NotSupportedException();
        }
    }
}


text:
%This function calculates the discrete derivative of a matrix in
%z-direction using forward finite differences.
%Right now, zero Dirichlet boundary conditions are used. For zero Neumann
%boundary conditions, uncomment the line in the middle.

function vwdiff = vwdiff_z(img)

[n m c] = size(img);
if (c~=1)
    for k=1:c-1
        vwdiff(:,:,k)=img(:,:,k+1)-img(:,:,k);
    end
    vwdiff(:,:,c)= -img(:,:,c);

    %vwdiff(:,:,c)=vwdiff(:,:,c-1);

else
    vwdiff=zeros(n,m);
end


text:
package org.netbeans.modeler.properties.customattr;

import java.awt.Frame;
import org.openide.util.Lookup;
import org.openide.util.Mutex;
import org.openide.windows.WindowManager;

public class Misc {

    private static Frame mainFrame = null;

    public static Frame getMainFrame() {
        if (mainFrame == null) {
            Runnable run = new Runnable() {

                @Override
                public void run() {
                    WindowManager w = Lookup.getDefault().lookup(WindowManager.class);
                    mainFrame = (w == null) ? null : w.getMainWindow();
                }
            };

            Mutex.EVENT.readAccess(run);
        }
        return mainFrame;
    }
}


text:
package org.apache.camel.component.lumberjack.springboot;

import org.apache.camel.util.jsse.SSLContextParameters;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

/**
 * The lumberjack retrieves logs sent over the network using the Lumberjack
 * protocol.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@ConfigurationProperties(prefix = "camel.component.lumberjack")
public class LumberjackComponentConfiguration {

    /**
     * Sets the default SSL configuration to use for all the endpoints. You can
     * also configure it directly at the endpoint level.
     */
    @NestedConfigurationProperty
    private SSLContextParameters sslContextParameters;
    /**
     * Whether the component should resolve property placeholders on itself when
     * starting. Only properties which are of String type can use property
     * placeholders.
     */
    private Boolean resolvePropertyPlaceholders = true;

    public SSLContextParameters getSslContextParameters() {
        return sslContextParameters;
    }

    public void setSslContextParameters(
            SSLContextParameters sslContextParameters) {
        this.sslContextParameters = sslContextParameters;
    }

    public Boolean getResolvePropertyPlaceholders() {
        return resolvePropertyPlaceholders;
    }

    public void setResolvePropertyPlaceholders(
            Boolean resolvePropertyPlaceholders) {
        this.resolvePropertyPlaceholders = resolvePropertyPlaceholders;
    }
}


text:
<?php
  require_once('LTI_Tool_Provider.php');

  mysql_connect("localhost", "lti" , "");
  mysql_select_db("lti_test");

  $db_connector = LTI_Data_Connector::getDataConnector('', 'MySQL');
  $consumer = new LTI_Tool_Consumer('testing.edu', $db_connector);
  $consumer->name = 'Testing';
  $consumer->secret = 'ThisIsASecret!';
  $consumer->save();
?>


text:
require 'ros/service'
require 'ros/tcpros/service_server'

module ROS

  # server of ROS Service.
  # {Node#advertise_service} return a instance of this class.
  # Service can be shutdown by {ServiceServer#shutdown}.
  # This class uses {TCPROS::ServiceServer} for data transfer.
  # @example
  #   node = ROS::Node.new('/rosruby/sample_service_server')
  #   server = node.advertise_service('/add_two_ints', Roscpp_tutorials::TwoInts) do |req, res|
  #     res.sum = req.a + req.b
  #     node.loginfo("a=#{req.a}, b=#{req.b}")
  #     node.loginfo("  sum = #{res.sum}")
  #     true
  #   end
  #   while node.ok?
  #     sleep (1.0)
  #   end
  class ServiceServer < Service

    # @param [String] caller_id caller id of this node
    # @param [String] service_name name of this service (String)
    # @param [Class] service_type class of srv
    # @param [Proc] callback callback object of this service.
    # @param [String] host host name
    def initialize(caller_id, service_name, service_type, callback, host)
      super(caller_id, service_name, service_type)
      @callback = callback
      @server = TCPROS::ServiceServer.new(@caller_id,
                                          @service_name,
                                          @service_type,
                                          self,
                                          :host => host)
      @server.start
      @num_request = 0
    end

    ##
    # execute the service callback.
    # User should not call this directly.
    # @param [Message] request srv Request instance
    # @param [Message] response srv Response instance
    # @return [Boolean] callback result
    def call(request, response)
      @num_request += 1
      @callback.call(request, response)
    end

    # URI of this service (rosrpc://**)
    # @return [String] rosrpc service uri
    def service_uri
      'rosrpc://' + @server.host + ':' + @server.port.to_s
    end

    ##
    # user should not call this method.
    # Please use shutdown method.
    def close #:nodoc:
      @server.shutdown
    end

    ##
    # shutdown the service connection
    #
    def shutdown
      @manager.shutdow_service_server(self)
    end

    # set GraphManager for shutdown
    # @param [GraphManager] manager set as manager
    def set_manager(manager) #:nodoc:
      @manager = manager
    end

    # @return [Array] connection data
    def get_connection_data
      [@num_request, @server.byte_received, @server.byte_sent]
    end

    # @return [Integer] how many times this service called
    attr_reader :num_request
  end
end


text:
layout: post
title: Learning PowerShell, Pitfalls for C# developers - Part 2
date: 2013-02-23 18:11:33.000000000 -05:00
category: coding
tags:
    - PowerShell
    - Scripting
author: Kevin Burdett
---
Continuing my post on learning PowerShell, I want to talk a bit about using parenthesis in PowerShell. They can be a bit confusing in PowerShell and generate some unexpected results for those coming from C#. There are two basic usages in PowerShell: grouping, and method calls. Grouping is just basic order of operations, so I don't really see the value in discussing it further. However, method calls in PowerShell are definitely worth discussing

# PowerShell Functions and Cmd-lets

Consider the following source code.

```powershell
function Get-Something ($foo, $bar)
{
    "1: $foo"
    "2: $bar"
}
```

For a C# developer, this might seem a bit odd though. The function declaration looks just like a C# declaration, minus the types. So it might make sense to call it just like a C# function, like so:

```powershell
function Get-Something ($foo, $bar)
{
    "1: $foo"
    "2: $bar"
}

Get-Something ('first', 'second')
```

Seems logical enough, except the part where this doesn't work... Naturally, we would expect this for an output:

    1: first
    2: second

Instead, we get this:

    1: first second
    2:

Definitely counter-intuitive, but easily understood with a little consideration. The parenthesis aren't defining the function arguments as you might expect in a language like C#, instead it is actually adding order of operations. PowerShell is evaluating the contents of the parenthesis and passing the results as an argument to the Get-Something function. Since we used a comma to separate our arguments, PowerShell conveniently turned it into an array for us and passed the resulting array as the first argument of the function. "Convenient," but not even close to what we wanted. Coincidentally, if we remove the comma we get something different entirely.

```powershell
function Get-Something ($foo, $bar)
{
    "1: $foo"
    "2: $bar"
}

Get-Something ('first' 'second')
```

This time we get an error.

    Unexpected token 'second' in expression or statement.
    At line:1 char:32
        + Get-Something ('first' 'second' <<<< )
        + CategoryInfo          : ParserError: (second:String) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken

PowerShell is still evaluating the contents of the parenthesis before calling the function, but by removing the comma, it just doesn't know what to do with them. This brings us to the proper way to call a PowerShell function or Cmd-Let, without the parenthesis!

```powershell
function Get-Something ($foo, $bar)
{
    return "$foo $bar"
}

Get-Something 'first' 'second'
```

And this gives us our expected output. Simple enough right? But wait, it doesn't stop there...

# .NET Functions

One of PowerShell's greatest selling features is the ability to use .NET natively. However, somebody decided that the parenthesis rules should be different for .NET objects. Whenever you call a method of an object, the parenthesis rules look much more like those in C#. Consider the following script.

```powershell
Get-Date | Get-Member
```

This outputs all of the members (methods and properties) present on the return value of the Get-Date function. The output looks like this:

	TypeName: System.DateTime

    Name                 MemberType     Definition
    ----                 ----------     ----------
    Add                  Method         System.DateTime Add(System.TimeSpan value)
    AddDays              Method         System.DateTime AddDays(double value)
    AddHours             Method         System.DateTime AddHours(double value)
    AddMilliseconds      Method         System.DateTime AddMilliseconds(double value)
    AddMinutes           Method         System.DateTime AddMinutes(double value)
    ...

.NET developers will undoubtedly be familiar with the System.DateTIme object and it's many methods. So let's say that we want to call one of these methods. For instance, we want to call the ToString function to output our current date and time in a specific format. Easy enough:

```powershell
$today = Get-Date
$today.ToString('g')
```

Naturally, this produces the simple output of the current date and time:

    2/23/2013 5:51 PM

So this is pretty much what a .NET developer would expect from a method call against a .NET object.

As a programmer, I found the dual usage of parenthesis a bit off-putting at first, but I suppose these kind of oddities are to be expected when mixing language paradigms though. After all, .NET is object oriented, while PowerShell is purely procedural. Weird, but it works!


text:
class Chef
  class Recipe
    class GPGCheck
      def self.check(file)
        pattern = /gpgcheck\s*=\s*0/

        return unless File.file?(file)

        File.open(file) do |f|
          f.each_line do |line|
            next unless pattern.match(line)
            Chef::Log.warn file + ': gpgcheck=1 not properly configured'
          end
        end
      end
    end
  end
end


text:
namespace android.webkit
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class WebViewClient : java.lang.Object
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		static WebViewClient()
		{
			InitJNI();
		}
		protected WebViewClient(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		internal static global::MonoJavaBridge.MethodId _shouldOverrideUrlLoading10676;
		public virtual bool shouldOverrideUrlLoading(android.webkit.WebView arg0, java.lang.String arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				return @__env.CallBooleanMethod(this.JvmHandle, global::android.webkit.WebViewClient._shouldOverrideUrlLoading10676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._shouldOverrideUrlLoading10676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _onPageStarted10677;
		public virtual void onPageStarted(android.webkit.WebView arg0, java.lang.String arg1, android.graphics.Bitmap arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onPageStarted10677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onPageStarted10677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _onPageFinished10678;
		public virtual void onPageFinished(android.webkit.WebView arg0, java.lang.String arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onPageFinished10678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onPageFinished10678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _onLoadResource10679;
		public virtual void onLoadResource(android.webkit.WebView arg0, java.lang.String arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onLoadResource10679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onLoadResource10679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _onTooManyRedirects10680;
		public virtual void onTooManyRedirects(android.webkit.WebView arg0, android.os.Message arg1, android.os.Message arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onTooManyRedirects10680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onTooManyRedirects10680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _onReceivedError10681;
		public virtual void onReceivedError(android.webkit.WebView arg0, int arg1, java.lang.String arg2, java.lang.String arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onReceivedError10681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onReceivedError10681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
		}
		internal static global::MonoJavaBridge.MethodId _onFormResubmission10682;
		public virtual void onFormResubmission(android.webkit.WebView arg0, android.os.Message arg1, android.os.Message arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onFormResubmission10682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onFormResubmission10682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _doUpdateVisitedHistory10683;
		public virtual void doUpdateVisitedHistory(android.webkit.WebView arg0, java.lang.String arg1, bool arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._doUpdateVisitedHistory10683, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._doUpdateVisitedHistory10683, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _onReceivedSslError10684;
		public virtual void onReceivedSslError(android.webkit.WebView arg0, android.webkit.SslErrorHandler arg1, android.net.http.SslError arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onReceivedSslError10684, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onReceivedSslError10684, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _onReceivedHttpAuthRequest10685;
		public virtual void onReceivedHttpAuthRequest(android.webkit.WebView arg0, android.webkit.HttpAuthHandler arg1, java.lang.String arg2, java.lang.String arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onReceivedHttpAuthRequest10685, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onReceivedHttpAuthRequest10685, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
		}
		internal static global::MonoJavaBridge.MethodId _shouldOverrideKeyEvent10686;
		public virtual bool shouldOverrideKeyEvent(android.webkit.WebView arg0, android.view.KeyEvent arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				return @__env.CallBooleanMethod(this.JvmHandle, global::android.webkit.WebViewClient._shouldOverrideKeyEvent10686, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._shouldOverrideKeyEvent10686, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _onUnhandledKeyEvent10687;
		public virtual void onUnhandledKeyEvent(android.webkit.WebView arg0, android.view.KeyEvent arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onUnhandledKeyEvent10687, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onUnhandledKeyEvent10687, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _onScaleChanged10688;
		public virtual void onScaleChanged(android.webkit.WebView arg0, float arg1, float arg2)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient._onScaleChanged10688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._onScaleChanged10688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
		}
		internal static global::MonoJavaBridge.MethodId _WebViewClient10689;
		public WebViewClient()  : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.webkit.WebViewClient.staticClass, global::android.webkit.WebViewClient._WebViewClient10689);
			Init(@__env, handle);
		}
		public static int ERROR_UNKNOWN
		{
			get
			{
				return -1;
			}
		}
		public static int ERROR_HOST_LOOKUP
		{
			get
			{
				return -2;
			}
		}
		public static int ERROR_UNSUPPORTED_AUTH_SCHEME
		{
			get
			{
				return -3;
			}
		}
		public static int ERROR_AUTHENTICATION
		{
			get
			{
				return -4;
			}
		}
		public static int ERROR_PROXY_AUTHENTICATION
		{
			get
			{
				return -5;
			}
		}
		public static int ERROR_CONNECT
		{
			get
			{
				return -6;
			}
		}
		public static int ERROR_IO
		{
			get
			{
				return -7;
			}
		}
		public static int ERROR_TIMEOUT
		{
			get
			{
				return -8;
			}
		}
		public static int ERROR_REDIRECT_LOOP
		{
			get
			{
				return -9;
			}
		}
		public static int ERROR_UNSUPPORTED_SCHEME
		{
			get
			{
				return -10;
			}
		}
		public static int ERROR_FAILED_SSL_HANDSHAKE
		{
			get
			{
				return -11;
			}
		}
		public static int ERROR_BAD_URL
		{
			get
			{
				return -12;
			}
		}
		public static int ERROR_FILE
		{
			get
			{
				return -13;
			}
		}
		public static int ERROR_FILE_NOT_FOUND
		{
			get
			{
				return -14;
			}
		}
		public static int ERROR_TOO_MANY_REQUESTS
		{
			get
			{
				return -15;
			}
		}
		private static void InitJNI()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.webkit.WebViewClient.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebViewClient"));
			global::android.webkit.WebViewClient._shouldOverrideUrlLoading10676 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "shouldOverrideUrlLoading", "(Landroid/webkit/WebView;Ljava/lang/String;)Z");
			global::android.webkit.WebViewClient._onPageStarted10677 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onPageStarted", "(Landroid/webkit/WebView;Ljava/lang/String;Landroid/graphics/Bitmap;)V");
			global::android.webkit.WebViewClient._onPageFinished10678 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onPageFinished", "(Landroid/webkit/WebView;Ljava/lang/String;)V");
			global::android.webkit.WebViewClient._onLoadResource10679 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onLoadResource", "(Landroid/webkit/WebView;Ljava/lang/String;)V");
			global::android.webkit.WebViewClient._onTooManyRedirects10680 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onTooManyRedirects", "(Landroid/webkit/WebView;Landroid/os/Message;Landroid/os/Message;)V");
			global::android.webkit.WebViewClient._onReceivedError10681 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onReceivedError", "(Landroid/webkit/WebView;ILjava/lang/String;Ljava/lang/String;)V");
			global::android.webkit.WebViewClient._onFormResubmission10682 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onFormResubmission", "(Landroid/webkit/WebView;Landroid/os/Message;Landroid/os/Message;)V");
			global::android.webkit.WebViewClient._doUpdateVisitedHistory10683 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "doUpdateVisitedHistory", "(Landroid/webkit/WebView;Ljava/lang/String;Z)V");
			global::android.webkit.WebViewClient._onReceivedSslError10684 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onReceivedSslError", "(Landroid/webkit/WebView;Landroid/webkit/SslErrorHandler;Landroid/net/http/SslError;)V");
			global::android.webkit.WebViewClient._onReceivedHttpAuthRequest10685 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onReceivedHttpAuthRequest", "(Landroid/webkit/WebView;Landroid/webkit/HttpAuthHandler;Ljava/lang/String;Ljava/lang/String;)V");
			global::android.webkit.WebViewClient._shouldOverrideKeyEvent10686 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "shouldOverrideKeyEvent", "(Landroid/webkit/WebView;Landroid/view/KeyEvent;)Z");
			global::android.webkit.WebViewClient._onUnhandledKeyEvent10687 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onUnhandledKeyEvent", "(Landroid/webkit/WebView;Landroid/view/KeyEvent;)V");
			global::android.webkit.WebViewClient._onScaleChanged10688 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "onScaleChanged", "(Landroid/webkit/WebView;FF)V");
			global::android.webkit.WebViewClient._WebViewClient10689 = @__env.GetMethodIDNoThrow(global::android.webkit.WebViewClient.staticClass, "<init>", "()V");
		}
	}
}


text:
package com.example.liangjie06.zuche.view.hotcity.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by liangjie06 on 17/3/13.
 */

public class AllCitySqliteOpenHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.liangjie06.zuche/databases/";
    private static String DB_NAME = "meituan_cities.db";
    private Context mContext;
    private static String ASSETS_NAME = "meituan_cities.db";
    private static final int DB_VERSION = 3;

    public AllCitySqliteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.mContext = context;
    }

    public AllCitySqliteOpenHelper(Context context, String name, int version){
        this(context, name, null, version);
    }

    public AllCitySqliteOpenHelper(Context context, String name) {
        this(context, name, DB_VERSION);
    }

    public AllCitySqliteOpenHelper(Context context){
        this(context, DB_PATH + DB_NAME);
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {

        } else {
            try {
                File dir = new File(DB_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File dbf = new File(DB_PATH + DB_NAME);
                if (dbf.exists()) {
                    Log.e("lj","数据库存在,我把它删了");
                    dbf.delete();
                    Log.e("lj","好了,我删完了");
                }
                Log.e("lj","我要打开");
                SQLiteDatabase.openOrCreateDatabase(dbf, null);
                Log.e("lj","我打开了");
                copyDataBase();
            } catch (IOException e) {
                throw new Error("数据库创建失败 ");
            }
        }
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        String myPath = DB_PATH + DB_NAME;
        try {
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException {
        // Open your local db as the input stream
        InputStream myInput = mContext.getAssets().open(ASSETS_NAME);
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


text:
FROM node:8.1.0-alpine
MAINTAINER Jonathan Griggs <jonathan.griggs@gmail.com>
ADD /src /app
WORKDIR /app
RUN npm install
CMD ["node", "index.js"]


text:
CREATE FUNCTION sp_reset_password
(
    resetCode VARCHAR(255),
    newPassword VARCHAR(255)
) RETURNS BOOLEAN AS $$

BEGIN
    UPDATE      app_users
    SET         password = newPassword
    FROM        app_password_reset
    WHERE       app_users.id = app_password_reset.user_id AND
                app_password_reset.code = resetCode;
    RETURN      FOUND;
END; $$ LANGUAGE plpgsql;


text:
/* Generic log function for debugging. */
var log = function(msg) { if (console && console.log) console.debug(msg); };

/**
 * Reload the display (get journal, render them)
 */
function reload() {
    var journalList = $("select:first");

    var getJournalsCB = function(journals) {
	// find the unordered list in our document to append to

	// clear the list
	journalList.html('');

	// populate the li`ast with our journal
	if (journals.length == 0) journalList.append("<option>Sorry, no journal(s) found!</option>");
        for (var i in journals) {
	    var journal = journals[i];

	    log(journal);

	    // get the journal name, but use the first email address if no name exists
	    var journalHTML = journal.id;

	    var optHTML = '<option id="' + journal._id + '" class="journal">'+journalHTML+'</div>';
	    journalList.append(optHTML);
	}
        journalList.attr("disabled", false);
    };

    var getJournalCB = function(journal) {

    };

    $.getJSON(
	'getJournals',
	{},
	getJournalsCB
    );

}

/* jQuery syntactic sugar for onDomReady */
$(function() {
    reload(0, 9000, true);
});


text:
exit_code=0

echo "*** Running annoyance gem specs"
bundle install --jobs=3 --retry=3 | grep Installing
bundle exec rspec spec
exit_code+=$?

exit $exit_code


text:
package com.google.ads.mediation.inmobi;

import static com.google.ads.mediation.inmobi.InMobiMediationAdapter.ERROR_DOMAIN;
import static com.google.ads.mediation.inmobi.InMobiMediationAdapter.ERROR_MALFORMED_IMAGE_URL;
import static com.google.ads.mediation.inmobi.InMobiMediationAdapter.ERROR_MISSING_NATIVE_ASSETS;
import static com.google.ads.mediation.inmobi.InMobiMediationAdapter.ERROR_NATIVE_ASSET_DOWNLOAD_FAILED;
import static com.google.ads.mediation.inmobi.InMobiMediationAdapter.TAG;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.ads.mediation.MediationNativeListener;
import com.google.android.gms.ads.mediation.UnifiedNativeAdMapper;
import com.inmobi.ads.InMobiNative;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

class InMobiUnifiedNativeAdMapper extends UnifiedNativeAdMapper {

  /**
   * InMobi native ad instance.
   */
  private final InMobiNative inMobiNative;

  /**
   * Flag to check whether urls are returned for image assets.
   */
  private final boolean isOnlyURL;

  /**
   * MediationNativeListener instance.
   */
  private final MediationNativeListener mediationNativeListener;

  /**
   * InMobi adapter instance.
   */
  private final InMobiAdapter inMobiAdapter;

  public InMobiUnifiedNativeAdMapper(InMobiAdapter inMobiAdapter, InMobiNative inMobiNative,
      Boolean isOnlyURL, MediationNativeListener mediationNativeListener) {
    this.inMobiAdapter = inMobiAdapter;
    this.inMobiNative = inMobiNative;
    this.isOnlyURL = isOnlyURL;
    this.mediationNativeListener = mediationNativeListener;
    setOverrideImpressionRecording(true);
  }

  // Map InMobi Native Ad to AdMob Unified Native Ad.
  void mapUnifiedNativeAd(final Context context) {

    if (!InMobiAdapterUtils.isValidNativeAd(inMobiNative)) {
      AdError error = new AdError(ERROR_MISSING_NATIVE_ASSETS,
          "InMobi native ad returned with a missing asset.", ERROR_DOMAIN);
      Log.w(TAG, error.getMessage());
      mediationNativeListener.onAdFailedToLoad(inMobiAdapter, error);
      return;
    }

    setHeadline(inMobiNative.getAdTitle());
    setBody(inMobiNative.getAdDescription());
    setCallToAction(inMobiNative.getAdCtaText());

    // App icon.
    final URL iconURL;
    final Uri iconUri;
    final double iconScale = 1.0;

    try {
      iconURL = new URL(inMobiNative.getAdIconUrl());
      iconUri = Uri.parse(iconURL.toURI().toString());
    } catch (MalformedURLException | URISyntaxException exception) {
      AdError error = new AdError(ERROR_MALFORMED_IMAGE_URL, exception.getLocalizedMessage(),
          ERROR_DOMAIN);
      Log.w(TAG, error.getMessage());
      mediationNativeListener.onAdFailedToLoad(inMobiAdapter, error);
      return;
    }

    HashMap<String, URL> map = new HashMap<>();
    String landingURL = inMobiNative.getAdLandingPageUrl();
    Bundle paramMap = new Bundle();
    paramMap.putString(InMobiNetworkValues.LANDING_URL, landingURL);
    setExtras(paramMap);

    if (!this.isOnlyURL) {
      map.put(ImageDownloaderAsyncTask.KEY_ICON, iconURL);
    } else {
      setIcon(new InMobiNativeMappedImage(null, iconUri, iconScale));
      List<NativeAd.Image> imagesList = new ArrayList<>();
      imagesList.add(
          new InMobiNativeMappedImage(new ColorDrawable(Color.TRANSPARENT), null, 1.0));
      setImages(imagesList);
    }

    // Optional assets.
    if (inMobiNative.getCustomAdContent() != null) {
      JSONObject payLoad = inMobiNative.getCustomAdContent();

      try {
        if (payLoad.has(InMobiNetworkValues.RATING)) {
          setStarRating(Double.parseDouble(payLoad.getString(InMobiNetworkValues.RATING)));
        }

        if (payLoad.has(InMobiNetworkValues.PRICE)) {
          setPrice(payLoad.getString(InMobiNetworkValues.PRICE));
        }
      } catch (JSONException jsonException) {
        Log.w(TAG, "InMobi custom native ad content payload could not be parsed. "
            + "The returned native ad will not have star rating or price values.");
      }

      if (payLoad.has(InMobiNetworkValues.PACKAGE_NAME)) {
        setStore("Google Play");
      } else {
        setStore("Others");
      }
    }

    // Add primary view as media view
    final RelativeLayout placeHolderView = new ClickInterceptorRelativeLayout(context);
    placeHolderView.setLayoutParams(
        new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    placeHolderView.setGravity(Gravity.CENTER);
    placeHolderView.post(
        new Runnable() {
          @Override
          public void run() {
            final View primaryView =
                inMobiNative.getPrimaryViewOfWidth(context, null, placeHolderView,
                    placeHolderView.getWidth());
            if (primaryView == null) {
              return;
            }

            placeHolderView.addView(primaryView);
            int viewHeight = primaryView.getLayoutParams().height;
            if (viewHeight > 0) {
              setMediaContentAspectRatio((float) primaryView.getLayoutParams().width / viewHeight);
            }
          }
        });

    setMediaView(placeHolderView);
    boolean hasVideo = (inMobiNative.isVideo() == null) ? false : inMobiNative.isVideo();
    setHasVideoContent(hasVideo);

    // Download drawables.
    if (!this.isOnlyURL) {
      new ImageDownloaderAsyncTask(
          new ImageDownloaderAsyncTask.DrawableDownloadListener() {
            @Override
            public void onDownloadSuccess(HashMap<String, Drawable> drawableMap) {
              Drawable iconDrawable = drawableMap.get(ImageDownloaderAsyncTask.KEY_ICON);
              setIcon(new InMobiNativeMappedImage(iconDrawable, iconUri, iconScale));

              List<NativeAd.Image> imagesList = new ArrayList<>();
              imagesList.add(
                  new InMobiNativeMappedImage(new ColorDrawable(Color.TRANSPARENT), null, 1.0));
              setImages(imagesList);

              if (null != iconDrawable) {
                mediationNativeListener.onAdLoaded(
                    inMobiAdapter, InMobiUnifiedNativeAdMapper.this);
              } else {
                AdError error = new AdError(ERROR_NATIVE_ASSET_DOWNLOAD_FAILED,
                    "Failed to download image assets.", ERROR_DOMAIN);
                Log.w(TAG, error.getMessage());
                mediationNativeListener.onAdFailedToLoad(inMobiAdapter, error);
              }
            }

            @Override
            public void onDownloadFailure() {
              AdError error = new AdError(ERROR_NATIVE_ASSET_DOWNLOAD_FAILED,
                  "Failed to download image assets.", ERROR_DOMAIN);
              Log.w(TAG, error.getMessage());
              mediationNativeListener.onAdFailedToLoad(inMobiAdapter, error);
            }
          })
          .execute(map);
    } else {
      mediationNativeListener.onAdLoaded(inMobiAdapter, InMobiUnifiedNativeAdMapper.this);
    }
  }

  @Override
  public void handleClick(@NonNull View view) {
    // Handle click.
    inMobiNative.reportAdClickAndOpenLandingPage();
  }

  @Override
  public void untrackView(@NonNull View view) {
    inMobiNative.pause();
  }

  @Override
  public void trackViews(@NonNull View containerView,
      @NonNull Map<String, View> clickableAssetViews,
      @NonNull Map<String, View> nonclickableAssetViews) {
    inMobiNative.resume();
  }
}


text:
---
id: 5e444147903586ffb414c94f
title: Calcolatore dell'area dei poligoni
challengeType: 10
forumTopicId: 462363
dashedName: polygon-area-calculator
---

# --description--

Lavorerari a [questo progetto con il nostro codice d'inizio su Replit](https://replit.com/github/freeCodeCamp/boilerplate-polygon-area-calculator).

Stiamo ancora sviluppando la parte didattica interattiva del curriculum di Python. Per ora, ecco alcuni video sul canale YouTube di freeCodeCamp.org che ti insegneranno tutto quello che devi sapere per completare questo progetto:

- [Video corso Python for Everybody](https://www.freecodecamp.org/news/python-for-everybody/) (14 ore)

- [Video corso Learn Python](https://www.freecodecamp.org/news/learn-python-video-course/) (10 ore)

# --instructions--

In questo progetto utilizzerai la programmazione orientata agli oggetti per creare una classe Rettangolo (Rectangle) e una classe Quadrato (Square). La classe Square dovrebbe essere una sottoclasse di Rectangle ed ereditare metodi ed attributi.

## Classe Rectangle

Quando viene creato un oggetto Rectangle, dovrebbe essere inizializzato con attributi `width` (larghezza) e `height` (altezza). La classe dovrebbe anche contenere i seguenti metodi:

- `set_width`
- `set_height`
- `get_area`: Restituisce l'area (`width * height`)
- `get_perimeter`: Restituisce il perimetro (`2 * width + 2 * height`)
- `get_diagonal`: Restituisce la diagonale (`(width ** 2 + height ** 2) ** .5`)
- `get_picture`: Restituisce una stringa che rappresenta la forma usando linee di "\*". Il numero di righe dovrebbe essere uguale all'altezza e il numero di "\*" in ogni riga dovrebbe essere uguale alla larghezza. Ci dovrebbe essere un carattere di nuova linea (`\n`) alla fine di ogni riga. Se la larghezza o l'altezza è maggiore di 50, questo dovrebbe restituire la stringa: `"Too big for picture."`.
- `get_amount_inside`: Prende un'altra forma (quadrato o rettangolo) come argomento. Restituisce il numero di volte che la forma passata potrebbe adattarsi all'interno della forma (senza rotazioni). Per esempio, un rettangolo con una larghezza di 4 e un'altezza di 8 potrebbe contenere due quadrati con lati di 4.

Inoltre, se un'istanza di Rectangle è rappresentata come una stringa, dovrebbe apparire come: `Rectangle(width=5, height=10)`

## Classe Square

La classe Square dovrebbe essere una sottoclasse di Rectangle. Quando viene creato un oggetto Square, viene passata la lunghezza di un singolo lato. Il metodo `__init__` dovrebbe memorizzare la lunghezza del lato sia nell'attributo `width` che in `height` della classe Rectangle.

La classe Square dovrebbe essere in grado di accedere ai metodi della classe Rectangle, ma dovrebbe anche contenere un metodo `set_side`. Se un'istanza di un quadrato è rappresentata come una stringa, dovrebbe apparire come `Square(side=9)`

Inoltre, i metodi `set_width` e `set_height` della classe Square dovrebbero impostare sia la larghezza che l'altezza.

## Esempio di utilizzo

```py
rect = shape_calculator.Rectangle(10, 5)
print(rect.get_area())
rect.set_height(3)
print(rect.get_perimeter())
print(rect)
print(rect.get_picture())

sq = shape_calculator.Square(9)
print(sq.get_area())
sq.set_side(4)
print(sq.get_diagonal())
print(sq)
print(sq.get_picture())

rect.set_height(8)
rect.set_width(16)
print(rect.get_amount_inside(sq))
```

Tale codice deve restituire:

```bash
50
26
Rectangle(width=10, height=3)
**********
**********
**********

81
5.656854249492381
Square(side=4)
****
****
****
****

8
```

I test unitari per questo progetto sono in `test_module.py`.

## Sviluppo

Scrivi il tuo codice in `shape_calculator.py`. Per lo sviluppo, puoi usare `main.py` per testare la tua funzione `shape_calculator()`. Usa il bottone "run" e `main.py` eseguirà.

## Test

Abbiamo importato i test da `test_module.py` in `main.py` per la tua convenienza. I test eseguiranno automaticamente quando usi il bottone "run".

## Invio

Copia l'URL del tuo progetto e consegnalo nell'input qua sotto.

# --hints--

Dovrebbe creare una classe Rectangle e una classe Square e superare tutti i test.

```js

```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
STYLE = default

less:
	lessc --clean-css="--s1 --advanced --compatibility=ie8" static/css/style.less > static/css/style.css

pygments:
	pygmentize -S ${STYLE} -f html > ./static/css/pygments.css


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web.notifier;

import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author Maciej "Gilek" Kłak
 */
public class Main {

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

                } catch (Exception ex) {
                    System.out.print(ex);
                    JOptionPane.showMessageDialog(null, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
                }

                new web.notifier.frames.LoginFrame().setVisible(true);
                //new WebNotifier();
            }
        });
    }
}


text:
// .NAME vtkBlockItem - a vtkContextItem that draws a block (optional label).
//
// .SECTION Description
// This is a vtkContextItem that can be placed into a vtkContextScene. It draws
// a block of the given dimensions, and reacts to mouse events.

#ifndef vtkBlockItem_h
#define vtkBlockItem_h

#include "vtkRenderingContext2DModule.h" // For export macro
#include "vtkContextItem.h"
#include "vtkStdString.h"    // For vtkStdString ivars

class vtkContext2D;

class VTKRENDERINGCONTEXT2D_EXPORT vtkBlockItem : public vtkContextItem
{
public:
  vtkTypeMacro(vtkBlockItem, vtkContextItem);
  virtual void PrintSelf(ostream &os, vtkIndent indent);

  static vtkBlockItem *New();

  // Description:
  // Paint event for the item.
  virtual bool Paint(vtkContext2D *painter);

//BTX
  // Description:
  // Returns true if the supplied x, y coordinate is inside the item.
  virtual bool Hit(const vtkContextMouseEvent &mouse);

  // Description:
  // Mouse enter event.
  virtual bool MouseEnterEvent(const vtkContextMouseEvent &mouse);

  // Description:
  // Mouse move event.
  virtual bool MouseMoveEvent(const vtkContextMouseEvent &mouse);

  // Description:
  // Mouse leave event.
  virtual bool MouseLeaveEvent(const vtkContextMouseEvent &mouse);

  // Description:
  // Mouse button down event.
  virtual bool MouseButtonPressEvent(const vtkContextMouseEvent &mouse);

  // Description:
  // Mouse button release event.
  virtual bool MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse);
//ETX

  // Description:
  // Set the block label.
  virtual void SetLabel(const vtkStdString &label);

  // Description:
  // Get the block label.
  virtual vtkStdString GetLabel();

  // Description:
  // Set the dimensions of the block, elements 0 and 1 are the x and y
  // coordinate of the bottom corner. Elements 2 and 3 are the width and
  // height.
  // Initial value is (0,0,0,0).
  vtkSetVector4Macro(Dimensions, float);

  // Description:
  // Get the dimensions of the block, elements 0 and 1 are the x and y
  // coordinate of the bottom corner. Elements 2 and 3 are the width and
  // height.
  // Initial value is (0,0,0,0)
  vtkGetVector4Macro(Dimensions, float);

//BTX
  void SetScalarFunctor(double (*scalarFunction)(double, double));
//ETX

//BTX
protected:
  vtkBlockItem();
  ~vtkBlockItem();

  float Dimensions[4];

  vtkStdString Label;

  bool MouseOver;

  // Some function pointers to optionally do funky things...
  double (*scalarFunction)(double, double);

private:
  vtkBlockItem(const vtkBlockItem &); // Not implemented.
  void operator=(const vtkBlockItem &);   // Not implemented.
//ETX
};

#endif //vtkBlockItem_h


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.locationtech.geomesa</groupId>
        <artifactId>geomesa-redis_2.11</artifactId>
        <version>3.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>

    <artifactId>geomesa-redis-datastore_2.11</artifactId>
    <name>GeoMesa Redis Datastore</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-index-api_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-feature-kryo_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-feature-avro_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-filter_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-cqengine_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-arrow-gt_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-security_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-process-vector_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <!-- provided -->

        <!-- test -->
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-core_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-junit_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-mock_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>

    </dependencies>

</project>


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

router.get('/', function (req, res) {
	utils.conlog(req.method, req.url);
	res.status(200).send('Node API home page');
});

module.exports = router;


text:
import {hasClass} from './../../helpers/dom/element';

export function normalizeSelection(selRange) {
  return {
    start: selRange.getTopLeftCorner(),
    end: selRange.getBottomRightCorner()
  };
}

export function isSeparator(cell) {
  return hasClass(cell, 'htSeparator');
}

export function hasSubMenu(cell) {
  return hasClass(cell, 'htSubmenu');
}

export function isDisabled(cell) {
  return hasClass(cell, 'htDisabled');
}

export function isSelectionDisabled(cell) {
  return hasClass(cell, 'htSelectionDisabled');
}

export function getValidSelection(hot) {
  let selected = hot.getSelected();

  if (!selected) {
    return null;
  }
  if (selected[0] < 0) {
    return null;
  }
  if (hot.countRows() >= hot.getSettings().maxRows) {
    return null;
  }

  return selected;
}

export function prepareVerticalAlignClass(className, alignment) {
  if (className.indexOf(alignment) != -1) {
    return className;
  }
  className = className
    .replace('htTop', '')
    .replace('htMiddle', '')
    .replace('htBottom', '')
    .replace('  ', '');

  className += ' ' + alignment;

  return className;
}

export function prepareHorizontalAlignClass(className, alignment) {
  if (className.indexOf(alignment) != -1) {
    return className;
  }
  className = className
    .replace('htLeft', '')
    .replace('htCenter', '')
    .replace('htRight', '')
    .replace('htJustify', '')
    .replace('  ', '');

  className += ' ' + alignment;

  return className;
}

export function getAlignmentClasses(range, callback) {
  const classes = {};

  for (let row = range.from.row; row <= range.to.row; row++) {
    for (let col = range.from.col; col <= range.to.col; col++) {
      if (!classes[row]) {
        classes[row] = [];
      }
      classes[row][col] = callback(row, col);
    }
  }

  return classes;
}

export function align(range, type, alignment, cellDescriptor) {
  if (range.from.row == range.to.row && range.from.col == range.to.col) {
    applyAlignClassName(range.from.row, range.from.col, type, alignment, cellDescriptor);
  } else {
    for (let row = range.from.row; row <= range.to.row; row++) {
      for (let col = range.from.col; col <= range.to.col; col++) {
        applyAlignClassName(row, col, type, alignment, cellDescriptor);
      }
    }
  }
}

function applyAlignClassName(row, col, type, alignment, cellDescriptor) {
  let cellMeta = cellDescriptor(row, col);
  let className = alignment;

  if (cellMeta.className) {
    if (type === 'vertical') {
      className = prepareVerticalAlignClass(cellMeta.className, alignment);
    } else {
      className = prepareHorizontalAlignClass(cellMeta.className, alignment);
    }
  }
  cellMeta.className = className;
}

export function checkSelectionConsistency(range, comparator) {
  let result = false;

  if (range) {
    range.forAll(function(row, col) {
      if (comparator(row, col)) {
        result = true;

        return false;
      }
    });
  }

  return result;
}

export function markLabelAsSelected(label) {
  // workaround for https://github.com/handsontable/handsontable/issues/1946
  return '' + String.fromCharCode(10003) + '' + label;
}


text:
// -----------------------------------------------------------------------
// <copyright file="TrackPage.xaml.cs" company="Nokia">
// Initial implementation by Steve Robbins from Nokia - http://twitter.com/sr_gb
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using ShufflerFM.Api;

namespace ShufflerFM
{
    /// <summary>
    /// The Track Page
    /// </summary>
    public partial class TrackPage : PhoneApplicationPage
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TrackPage"/> class.
        /// </summary>
        public TrackPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Gets or sets the target track.
        /// </summary>
        /// <value>
        /// The target track.
        /// </value>
        public Track TargetTrack { get; set; }

        /// <summary>
        /// Called when a page becomes the active page in a frame.
        /// </summary>
        /// <param name="e">An object that contains the event data.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.NavigationMode == NavigationMode.New)
            {
                this.TargetTrack = App.SelectedItem as Track;
                this.TargetTrack.Artist.AttemptNokiaLookup();
            }
        }

        /// <summary>
        /// Plays the artist mix.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void PlayArtistMix(object sender, RoutedEventArgs e)
        {
            this.TargetTrack.Artist.PlayMixInNokiaMusic();
        }

        /// <summary>
        /// Opens web links
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void OpenWebLink(object sender, RoutedEventArgs e)
        {
            FrameworkElement elem = sender as FrameworkElement;
            if (elem != null)
            {
                Uri link = elem.Tag as Uri;
                if (link != null)
                {
                    new WebBrowserTask() { Uri = link }.Show();
                }
            }
        }
    }
}


text:
<?xml version="1.0"?>

<iati-organisations version="xx">

  <iati-organisation>
    <organisation-identifier>12345</organisation-identifier>
    <name>
      <narrative>Name here</narrative>
    </name>
    <reporting-org type="xx" ref="xx">
      <narrative>Organisation name</narrative>
    </reporting-org>

    <total-budget> <!-- optional-->
      <period-start iso-date="2014-01-31" /> <!-- must have 1 and only 1 -->
      <period-end iso-date="2014-03-31" /> <!-- must have 1 and only 1 -->
      <value value-date="2011-0101">100.23</value> <!-- must have 1 and only 1 -->
    </total-budget>

  </iati-organisation>

</iati-organisations>


text:
// @target: es6

function f(x: TemplateStringsArray, y: string, z: string) {
}

// Incomplete call, not enough parameters, at EOF.
f `


text:
layout: post
title: "Scrum Complexity Points"
description: ""
category:
tags: ['scrum', 'story points']
---

# Scrum Complexity points

There's a lot of debate on how story points should be estimated.

Personally, coming from a mixed Dev / Ops / DevOps SRE background, I find the following the most effective.

This doesn't work for everyone and by no means is the authority.

But it works for me.

![image](/assets/images/Complexity_Points_Indifference.png)


text:
package com.cvsintellect.servlet.user;

import java.io.IOException;

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

import com.cvsintellect.db.cache.CacheService;
import com.cvsintellect.db.dao.EntryDAO;
import com.cvsintellect.db.dao.UserDataDAO;
import com.cvsintellect.db.model.AbstractDTO;
import com.cvsintellect.db.model.UserDTO;
import com.cvsintellect.servlet.constants.KeyConstants;
import com.cvsintellect.servlet.constants.MessageConstants;
import com.cvsintellect.servlet.constants.ResourceConstants;
import com.cvsintellect.servlet.util.AjaxResponse;
import com.google.appengine.api.datastore.Key;

public class Move extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Move() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);

		Key userId = (Key) session.getAttribute(KeyConstants.USER_ID.toString());

		String resource = request.getPathInfo();

		try {
			UserDTO userData = new UserDataDAO(new CacheService()).getUserDataByKey(userId);

			if (resource.equals(ResourceConstants.ENTRY)) {
				String keyDigest = request.getParameter("entry[keyDigest]");
				String direction = request.getParameter("entry[direction]");

				int index = AbstractDTO.getIndexOf(userData.getEntries(), keyDigest);

				if (index == -1) {
					AjaxResponse.writeFailureOutput(response, MessageConstants.CANNOT_FIND_OBJECT_AT_INDEX);
					return;
				}

				new EntryDAO(new CacheService()).moveEntry(userId, index, direction);

				AjaxResponse.writeSuccessOutput(response);
				return;
			}
		}
		catch (Exception e) {
			AjaxResponse.writeFailureOutput(response, MessageConstants.GENERIC_ERROR_MESSAGE);
			return;
		}
	}
}


text:
<?php

/**
 * JobTypeTable
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class JobTypeTable extends Doctrine_Table
{
    /**
     * Returns an instance of this class.
     *
     * @return object JobTypeTable
     */
    public static function getInstance()
    {
        return Doctrine_Core::getTable('JobType');
    }

	public function retrieveBackendJobType(Doctrine_Query $q)
	{
		$r = $q->getRootAlias();
		$q
			->where($r.'.job_type_id > 1')
			->leftJoin($r.'.Translation t');
		return $q;
	}
}


text:
require 'skype_api/msg_request'

describe SkypeApi::MsgRequest do
  it "exist" do
    SkypeApi::MsgRequest.should be
  end

  it "reply for user message" do
    SkypeApi::MsgRequest.reply("Hello world!").should == "Hello world!"
  end
end