text:
package blue.lapis.pore.impl.entity;

import blue.lapis.pore.converter.vector.VectorConverter;
import blue.lapis.pore.converter.wrapper.WrapperConverter;

import org.apache.commons.lang3.NotImplementedException;
import org.bukkit.entity.EntityType;
import org.bukkit.util.Vector;
import org.spongepowered.api.entity.projectile.explosive.ExplosiveProjectile;

public class PoreFireball extends PoreProjectile implements org.bukkit.entity.Fireball {

    public static PoreFireball of(ExplosiveProjectile handle) {
        return WrapperConverter.of(PoreFireball.class, handle);
    }

    protected PoreFireball(ExplosiveProjectile handle) {
        super(handle);
    }

    @Override
    public ExplosiveProjectile getHandle() {
        return (ExplosiveProjectile) super.getHandle();
    }

    @Override
    public EntityType getType() {
        return EntityType.FIREBALL;
    }

    @Override
    public Vector getDirection() {
        //TODO: I'm not entirely sure how this method is supposed to behave, so this impl might change
        return VectorConverter.getUnitVector(this.getVelocity()).multiply(0.1);
    }

    @Override
    public void setDirection(Vector direction) {
        throw new NotImplementedException("TODO");
    }

    @Override
    public float getYield() { // TODO: ???
        return getHandle().getExplosiveRadiusData().explosiveRadius().get();
    }

    @Override
    public void setYield(float yield) {
        getHandle().offer(getHandle().getExplosiveRadiusData().explosiveRadius().set((int) yield));
    }

    @Override
    public boolean isIncendiary() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setIsIncendiary(boolean isIncendiary) {
        throw new NotImplementedException("TODO");
    }

}


text:
package de.frosner.broccoli.nomad.models

import enumeratum._

import scala.collection.immutable

/**
  * The nomad client status.
  *
  * Presumably this is the status the allocation
  *
  * See https://github.com/hashicorp/nomad/blob/2e7d8adfa4e9cbbc85009943f79641ac55875aa6/nomad/structs/structs.go#L4260
  * for all possible values.
  */
sealed trait ClientStatus extends EnumEntry with EnumEntry.Lowercase

object ClientStatus extends Enum[ClientStatus] with PlayJsonEnum[ClientStatus] {

  override val values: immutable.IndexedSeq[ClientStatus] = findValues

  case object Pending extends ClientStatus
  case object Running extends ClientStatus
  case object Complete extends ClientStatus
  case object Failed extends ClientStatus
  case object Lost extends ClientStatus
}

redpajama_set_name: RedPajamaGithub


text:
package utils

import (
	"crypto/x509"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"strings"

	"github.com/gravitational/teleport"

	"github.com/gravitational/kingpin"
	"github.com/gravitational/trace"
	log "github.com/sirupsen/logrus"
)

type LoggingPurpose int

const (
	LoggingForDaemon LoggingPurpose = iota
	LoggingForCLI
	LoggingForTests
)

// InitLogger configures the global logger for a given purpose / verbosity level
func InitLogger(purpose LoggingPurpose, level log.Level, verbose ...bool) {
	log.StandardLogger().SetHooks(make(log.LevelHooks))
	formatter := &trace.TextFormatter{DisableTimestamp: true}
	log.SetFormatter(formatter)
	log.SetLevel(level)

	switch purpose {
	case LoggingForCLI:
		// If debug logging was asked for on the CLI, then write logs to stderr.
		// Otherwise discard all logs.
		if level == log.DebugLevel {
			log.SetOutput(os.Stderr)
		} else {
			log.SetOutput(ioutil.Discard)
		}
	case LoggingForDaemon:
		log.SetOutput(os.Stderr)
	case LoggingForTests:
		log.SetLevel(level)
		if len(verbose) != 0 && verbose[0] {
			return
		}
		val, _ := strconv.ParseBool(os.Getenv(teleport.VerboseLogsEnvVar))
		if val {
			return
		}
		val, _ = strconv.ParseBool(os.Getenv(teleport.DebugEnvVar))
		if val {
			return
		}
		log.SetLevel(log.WarnLevel)
		log.SetOutput(ioutil.Discard)
	}
}

func InitLoggerForTests(verbose ...bool) {
	InitLogger(LoggingForTests, log.DebugLevel, verbose...)
}

// FatalError is for CLI front-ends: it detects gravitational/trace debugging
// information, sends it to the logger, strips it off and prints a clean message to stderr
func FatalError(err error) {
	fmt.Fprintln(os.Stderr, UserMessageFromError(err))
	os.Exit(1)
}

// UserMessageFromError returns user friendly error message from error
func UserMessageFromError(err error) string {
	// untrusted cert?
	switch innerError := trace.Unwrap(err).(type) {
	case x509.HostnameError:
		return fmt.Sprintf("Cannot establish https connection to %s:\n%s\n%s\n",
			innerError.Host,
			innerError.Error(),
			"try a different hostname for --proxy or specify --insecure flag if you know what you're doing.")
	case x509.UnknownAuthorityError:
		return `WARNING:

  The proxy you are connecting to has presented a certificate signed by a
  unknown authority. This is most likely due to either being presented
  with a self-signed certificate or the certificate was truly signed by an
  authority not known to the client.

  If you know the certificate is self-signed and would like to ignore this
  error use the --insecure flag.

  If you have your own certificate authority that you would like to use to
  validate the certificate chain presented by the proxy, set the
  SSL_CERT_FILE and SSL_CERT_DIR environment variables respectively and try
  again.

  If you think something malicious may be occurring, contact your Teleport
  system administrator to resolve this issue.
`
	case x509.CertificateInvalidError:
		return fmt.Sprintf(`WARNING:

  The certificate presented by the proxy is invalid: %v.

  Contact your Teleport system administrator to resolve this issue.`, innerError)
	}
	if log.GetLevel() == log.DebugLevel {
		return trace.DebugReport(err)
	}
	if err != nil {
		// If the error is a trace error, check if it has a user message embedded in
		// it. If a user message is embedded in it, print the user message and the
		// original error. Otherwise return the original with a generic "A fatal
		// error occurred" message.
		if er, ok := err.(*trace.TraceErr); ok {
			if er.Message != "" {
				return fmt.Sprintf("error: %v", er.Message)
			}
		}
		return fmt.Sprintf("error: %v", err.Error())
	}
	return ""
}

// Consolef prints the same message to a 'ui console' (if defined) and also to
// the logger with INFO priority
func Consolef(w io.Writer, component string, msg string, params ...interface{}) {
	entry := log.WithFields(log.Fields{
		trace.Component: component,
	})
	msg = fmt.Sprintf(msg, params...)
	entry.Info(msg)
	if w != nil {
		component := strings.ToUpper(component)
		fmt.Fprintf(w, "[%v]%v%v\n", strings.ToUpper(component), strings.Repeat(" ", 8-len(component)), msg)
	}
}

// InitCLIParser configures kingpin command line args parser with
// some defaults common for all Teleport CLI tools
func InitCLIParser(appName, appHelp string) (app *kingpin.Application) {
	app = kingpin.New(appName, appHelp)

	// hide "--help" flag
	app.HelpFlag.Hidden()
	app.HelpFlag.NoEnvar()

	// set our own help template
	return app.UsageTemplate(defaultUsageTemplate)
}

// Usage template with compactly formatted commands.
var defaultUsageTemplate = `{{define "FormatCommand"}}\
{{if .FlagSummary}} {{.FlagSummary}}{{end}}\
{{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\
{{end}}\

{{define "FormatCommands"}}\
{{range .FlattenedCommands}}\
{{if not .Hidden}}\
  {{.FullCommand | printf "%-12s" }}{{if .Default}} (Default){{end}} {{ .Help }}
{{end}}\
{{end}}\
{{end}}\

{{define "FormatUsage"}}\
{{template "FormatCommand" .}}{{if .Commands}} <command> [<args> ...]{{end}}
{{if .Help}}
{{.Help|Wrap 0}}\
{{end}}\

{{end}}\

{{if .Context.SelectedCommand}}\
usage: {{.App.Name}} {{.Context.SelectedCommand}}{{template "FormatUsage" .Context.SelectedCommand}}
{{else}}\
Usage: {{.App.Name}}{{template "FormatUsage" .App}}
{{end}}\
{{if .Context.Flags}}\
Flags:
{{.Context.Flags|FlagsToTwoColumnsCompact|FormatTwoColumns}}
{{end}}\
{{if .Context.Args}}\
Args:
{{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}}
{{end}}\
{{if .Context.SelectedCommand}}\

{{ if .Context.SelectedCommand.Commands}}\
Commands:
{{if .Context.SelectedCommand.Commands}}\
{{template "FormatCommands" .Context.SelectedCommand}}
{{end}}\
{{end}}\

{{else if .App.Commands}}\
Commands:
{{template "FormatCommands" .App}}
Try '{{.App.Name}} help [command]' to get help for a given command.
{{end}}\

{{ if .Context.SelectedCommand }}\
{{ range .Context.SelectedCommand.Aliases}}\
{{ . }}
{{end}}\
{{end}}
`


text:
namespace {

std::pair<std::string, size_t> GetVersionFromString(
    const std::string& version_string,
    size_t begin = 0) {
  begin = version_string.find_first_of("0123456789", begin);
  if (begin == std::string::npos)
    return std::make_pair("", std::string::npos);

  size_t end = version_string.find_first_not_of("01234567890.", begin);
  std::string sub_string;
  if (end != std::string::npos)
    sub_string = version_string.substr(begin, end - begin);
  else
    sub_string = version_string.substr(begin);
  std::vector<std::string> pieces = base::SplitString(
      sub_string, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  if (pieces.size() >= 2)
    return std::make_pair(pieces[0] + "." + pieces[1], end);
  else
    return std::make_pair("", end);
}

std::string GetDriverVersionFromString(const std::string& version_string) {
  // We expect that android GL_VERSION strings will be of a form
  // similar to: "OpenGL ES 2.0 V@6.0 AU@ (CL@2946718)" where the
  // first match to [0-9][0-9.]* is the OpenGL ES version number, and
  // the second match to [0-9][0-9.]* is the driver version (in this
  // case, 6.0).
  // It is currently assumed that the driver version has at least one
  // period in it, and only the first two components are significant.
  size_t begin = GetVersionFromString(version_string).second;
  if (begin == std::string::npos)
    return "0";

  std::pair<std::string, size_t> driver_version =
      GetVersionFromString(version_string, begin);
  if (driver_version.first == "")
    return "0";

  return driver_version.first;
}

gpu::CollectInfoResult CollectDriverInfo(gpu::GPUInfo* gpu_info) {
  // Go through the process of loading GL libs and initializing an EGL
  // context so that we can get GL vendor/version/renderer strings.
  base::NativeLibrary gles_library, egl_library;
  base::NativeLibraryLoadError error;
  gles_library =
      base::LoadNativeLibrary(base::FilePath("libGLESv2.so"), &error);
  if (!gles_library)
    LOG(FATAL) << "Failed to load libGLESv2.so";

  egl_library = base::LoadNativeLibrary(base::FilePath("libEGL.so"), &error);
  if (!egl_library)
    LOG(FATAL) << "Failed to load libEGL.so";

  typedef void* (*eglGetProcAddressProc)(const char* name);

  auto eglGetProcAddressFn = reinterpret_cast<eglGetProcAddressProc>(
      base::GetFunctionPointerFromNativeLibrary(egl_library,
                                                "eglGetProcAddress"));
  if (!eglGetProcAddressFn)
    LOG(FATAL) << "eglGetProcAddress not found.";

  auto get_func = [eglGetProcAddressFn, gles_library, egl_library](
      const char* name) {
    void *proc;
    proc = base::GetFunctionPointerFromNativeLibrary(egl_library, name);
    if (proc)
      return proc;
    proc = base::GetFunctionPointerFromNativeLibrary(gles_library, name);
    if (proc)
      return proc;
    proc = eglGetProcAddressFn(name);
    if (proc)
      return proc;
    LOG(FATAL) << "Failed to look up " << name;
    return (void *)nullptr;
  };

#define LOOKUP_FUNC(x) auto x##Fn = reinterpret_cast<gfx::x##Proc>(get_func(#x))

  LOOKUP_FUNC(eglGetError);
  LOOKUP_FUNC(eglQueryString);
  LOOKUP_FUNC(eglGetCurrentContext);
  LOOKUP_FUNC(eglGetCurrentDisplay);
  LOOKUP_FUNC(eglGetCurrentSurface);
  LOOKUP_FUNC(eglGetDisplay);
  LOOKUP_FUNC(eglInitialize);
  LOOKUP_FUNC(eglChooseConfig);
  LOOKUP_FUNC(eglCreateContext);
  LOOKUP_FUNC(eglCreatePbufferSurface);
  LOOKUP_FUNC(eglMakeCurrent);
  LOOKUP_FUNC(eglDestroySurface);
  LOOKUP_FUNC(eglDestroyContext);

  LOOKUP_FUNC(glGetString);
  LOOKUP_FUNC(glGetIntegerv);

#undef LOOKUP_FUNC

  EGLDisplay curr_display = eglGetCurrentDisplayFn();
  EGLContext curr_context = eglGetCurrentContextFn();
  EGLSurface curr_draw_surface = eglGetCurrentSurfaceFn(EGL_DRAW);
  EGLSurface curr_read_surface = eglGetCurrentSurfaceFn(EGL_READ);

  EGLDisplay temp_display = EGL_NO_DISPLAY;
  EGLContext temp_context = EGL_NO_CONTEXT;
  EGLSurface temp_surface = EGL_NO_SURFACE;

  const EGLint kConfigAttribs[] = {
      EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
      EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
      EGL_NONE};
  const EGLint kContextAttribs[] = {
      EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT,
          EGL_LOSE_CONTEXT_ON_RESET_EXT,
      EGL_CONTEXT_CLIENT_VERSION, 2,
      EGL_NONE};
  const EGLint kSurfaceAttribs[] = {
      EGL_WIDTH, 1,
      EGL_HEIGHT, 1,
      EGL_NONE};

  EGLint major, minor;

  EGLConfig config;
  EGLint num_configs;

  auto errorstr = [eglGetErrorFn]() {
    uint32_t err = eglGetErrorFn();
    return base::StringPrintf("%s (%x)", ui::GetEGLErrorString(err), err);
  };

  temp_display = eglGetDisplayFn(EGL_DEFAULT_DISPLAY);

  if (temp_display == EGL_NO_DISPLAY) {
    LOG(FATAL) << "failed to get display. " << errorstr();
  }

  eglInitializeFn(temp_display, &major, &minor);

  bool egl_create_context_robustness_supported =
      strstr(reinterpret_cast<const char*>(
                 eglQueryStringFn(temp_display, EGL_EXTENSIONS)),
             "EGL_EXT_create_context_robustness") != NULL;

  if (!eglChooseConfigFn(temp_display, kConfigAttribs, &config, 1,
                         &num_configs)) {
    LOG(FATAL) << "failed to choose an egl config. " << errorstr();
  }

  temp_context = eglCreateContextFn(
      temp_display, config, EGL_NO_CONTEXT,
      kContextAttribs + (egl_create_context_robustness_supported ? 0 : 2));
  if (temp_context == EGL_NO_CONTEXT) {
    LOG(FATAL)
        << "failed to create a temporary context for fetching driver strings. "
        << errorstr();
  }

  temp_surface =
      eglCreatePbufferSurfaceFn(temp_display, config, kSurfaceAttribs);

  if (temp_surface == EGL_NO_SURFACE) {
    eglDestroyContextFn(temp_display, temp_context);
    LOG(FATAL)
        << "failed to create a pbuffer surface for fetching driver strings. "
        << errorstr();
  }

  eglMakeCurrentFn(temp_display, temp_surface, temp_surface, temp_context);

  gpu_info->gl_vendor = reinterpret_cast<const char*>(glGetStringFn(GL_VENDOR));
  gpu_info->gl_version =
      reinterpret_cast<const char*>(glGetStringFn(GL_VERSION));
  gpu_info->gl_renderer =
      reinterpret_cast<const char*>(glGetStringFn(GL_RENDERER));
  gpu_info->gl_extensions =
      reinterpret_cast<const char*>(glGetStringFn(GL_EXTENSIONS));

  GLint max_samples = 0;
  glGetIntegervFn(GL_MAX_SAMPLES, &max_samples);
  gpu_info->max_msaa_samples = base::IntToString(max_samples);

  bool supports_robustness =
      gpu_info->gl_extensions.find("GL_EXT_robustness") != std::string::npos ||
      gpu_info->gl_extensions.find("GL_KHR_robustness") != std::string::npos ||
      gpu_info->gl_extensions.find("GL_ARB_robustness") != std::string::npos;

  if (supports_robustness) {
    glGetIntegervFn(
        GL_RESET_NOTIFICATION_STRATEGY_ARB,
        reinterpret_cast<GLint*>(&gpu_info->gl_reset_notification_strategy));
  }

  std::string glsl_version_string;
  if (const char* glsl_version_cstring = reinterpret_cast<const char*>(
          glGetStringFn(GL_SHADING_LANGUAGE_VERSION)))
    glsl_version_string = glsl_version_cstring;

  std::string glsl_version = GetVersionFromString(glsl_version_string).first;
  gpu_info->pixel_shader_version = glsl_version;
  gpu_info->vertex_shader_version = glsl_version;

  if (curr_display != EGL_NO_DISPLAY &&
      curr_context != EGL_NO_CONTEXT) {
    eglMakeCurrentFn(curr_display, curr_draw_surface, curr_read_surface,
                     curr_context);
  } else {
    eglMakeCurrentFn(temp_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
                     EGL_NO_CONTEXT);
  }

  eglDestroySurfaceFn(temp_display, temp_surface);
  eglDestroyContextFn(temp_display, temp_context);

  return gpu::kCollectInfoSuccess;
}

}

namespace gpu {

CollectInfoResult CollectContextGraphicsInfo(GPUInfo* gpu_info) {
  /// TODO(tobiasjs) Check if CollectGraphicsInfo in gpu_main.cc
  /// really only needs basic graphics info on all platforms, and if
  /// so switch it to using that and make this the NOP that it really
  /// should be, to avoid potential double collection of info.
  return CollectBasicGraphicsInfo(gpu_info);
}

CollectInfoResult CollectGpuID(uint32_t* vendor_id, uint32_t* device_id) {
  DCHECK(vendor_id && device_id);
  *vendor_id = 0;
  *device_id = 0;
  return kCollectInfoNonFatalFailure;
}

CollectInfoResult CollectBasicGraphicsInfo(GPUInfo* gpu_info) {
  gpu_info->can_lose_context = false;

  // When command buffer is compiled as a standalone library, the process might
  // not have a Java environment.
  if (base::android::IsVMInitialized()) {
    gpu_info->machine_model_name =
        base::android::BuildInfo::GetInstance()->model();
  }

  // Create a short-lived context on the UI thread to collect the GL strings.
  // Make sure we restore the existing context if there is one.
  CollectInfoResult result = CollectDriverInfo(gpu_info);
  if (result == kCollectInfoSuccess)
    result = CollectDriverInfoGL(gpu_info);
  gpu_info->basic_info_state = result;
  gpu_info->context_info_state = result;
  return result;
}

CollectInfoResult CollectDriverInfoGL(GPUInfo* gpu_info) {
  gpu_info->driver_version = GetDriverVersionFromString(
      gpu_info->gl_version);
  gpu_info->gpu.vendor_string = gpu_info->gl_vendor;
  gpu_info->gpu.device_string = gpu_info->gl_renderer;
  return kCollectInfoSuccess;
}

void MergeGPUInfo(GPUInfo* basic_gpu_info,
                  const GPUInfo& context_gpu_info) {
  MergeGPUInfoGL(basic_gpu_info, context_gpu_info);
}

}  // namespace gpu


text:
import os
import argparse
import re
from glob import glob

import numpy
from matplotlib import pyplot

class DataObject(object):
    def __init__(self, file_pattern, log_pattern):
        self.files = glob(file_pattern)
        self.regex = re.compile(log_pattern)

        self.data_dict = {}
        for file in self.files:
            with open(file, 'r') as f:
                lines = f.readlines()
            matches = numpy.float32(numpy.array([self.regex.findall(line)[0] for line in lines if self.regex.findall(line)]))
            self.data_dict[file] = matches

    def plot(self):
        for key, value in self.data_dict.iteritems():
            pyplot.plot(value, label=key)

        pyplot.legend()
        pyplot.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='log plotter',
                                     description='Script to plot log data.')

    parser.add_argument('file_pattern', help='Pattern for matching log files.')
    parser.add_argument('log_pattern', help='Pattern for getting data values.')

    args = parser.parse_args()

    # file_pattern = '*.txt'
    # log_pattern = '[0-9] (.*)'
    do = DataObject(args.file_pattern, args.log_pattern)
    do.plot()


text:
share
-----

* Description: Get a full table of all your projects with the xip.io url
* Usage:

  * `share [--hideLogo] [--no-interactive]`

The <info>share</info> command show a table of all your locally installed projects together with the xip.io url.

<info>php skylab.phar share</info>                         # Will show the xip.io table

### Options:

**hideLogo:**

* Name: `--hideLogo`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: If set, no logo or statistics will be shown
* Default: `false`

**no-interactive:**

* Name: `--no-interactive`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: If set, no questions will be asked
* Default: `false`

**help:**

* Name: `--help`
* Shortcut: `-h`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this help message
* Default: `false`

**quiet:**

* Name: `--quiet`
* Shortcut: `-q`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not output any message
* Default: `false`

**verbose:**

* Name: `--verbose`
* Shortcut: `-v|-vv|-vvv`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
* Default: `false`

**version:**

* Name: `--version`
* Shortcut: `-V`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this application version
* Default: `false`

**ansi:**

* Name: `--ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Force ANSI output
* Default: `false`

**no-ansi:**

* Name: `--no-ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Disable ANSI output
* Default: `false`

**no-interaction:**

* Name: `--no-interaction`
* Shortcut: `-n`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not ask any interactive question
* Default: `false`

*Documentation generated on 2015-08-09 17:44:20*


text:
var mdeps = require('../');
var test = require('tap').test;
var JSONStream = require('JSONStream');
var packer = require('browser-pack');
var concat = require('concat-stream');

test('pkg filter', function (t) {
    t.plan(2);

    var p = mdeps(__dirname + '/files/pkg_filter/test.js', {
        packageFilter: function (pkg) {
            t.equal(pkg.main, 'one.js');
            pkg.main = 'two.js'
            return pkg;
        }
    });
    var pack = packer();
    p.pipe(JSONStream.stringify()).pipe(pack);

    pack.pipe(concat(function (src) {
        Function('t', src)(t);
    }));
});


text:
use crate::wire_format::WireType;
use crate::CodedInputStream;
use crate::CodedOutputStream;
use crate::Message;
use crate::MessageField;

/// Read singular `message` field.
pub fn read_singular_message_into_field<M>(
    is: &mut CodedInputStream,
    target: &mut MessageField<M>,
) -> crate::Result<()>
where
    M: Message,
{
    let mut m = M::new();
    is.merge_message(&mut m)?;
    *target = MessageField::some(m);
    Ok(())
}

/// Write message with field number and length to the stream.
pub fn write_message_field_with_cached_size<M>(
    field_number: u32,
    message: &M,
    os: &mut CodedOutputStream,
) -> crate::Result<()>
where
    M: Message,
{
    os.write_tag(field_number, WireType::LengthDelimited)?;
    os.write_raw_varint32(message.cached_size())?;
    message.write_to_with_cached_sizes(os)
}


text:
/* Swedish translation for the jQuery Timepicker Addon */
/* Written by Nevon */
(function($) {
	$.timepicker.regional['sv'] = {
		timeOnlyTitle: 'Välj en tid',
		timeText: 'Timme',
		hourText: 'Timmar',
		minuteText: 'Minuter',
		secondText: 'Sekunder',
		millisecText: 'Millisekunder',
		timezoneText: 'Tidszon',
		currentText: 'Nu',
		closeText: 'Stäng',
		timeFormat: 'HH:mm',
		amNames: ['AM', 'A'],
		pmNames: ['PM', 'P'],
		isRTL: false
	};
	$.timepicker.setDefaults($.timepicker.regional['sv']);
})(jQuery);


text:
title: Upcoming Changes with PhoneGap 2.1 & iOS 6
date: 2012-08-29 18:17:45 Z
tags:
- PhoneGap Network
external: true
author: Andrew Trice
link: http://www.tricedesigns.com/2012/08/29/upcoming-changes-with-phonegap-2-1-ios-6/
status: publish
type: post
format: html
---

Are you using PhoneGap/Apache Cordova for iOS development?  If so, you'll definitely want to pay attention to the upcoming PhoneGap 2.1 release. If you haven't seen it already, be sure to check out Shazron's post: 11 upcoming changes for Cordova iOS 2.1.  Changes include Automatic Rererecnce Counting (ARC) support, an updated Native-JavaScript bridge, diagnostics, and [...]


text:
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on October 5, 2014 */

@font-face {
    font-family: 'maven_pro_light200';
    src: url('mavenprolight-200-webfont.eot');
    src: url('mavenprolight-200-webfont.eot?#iefix') format('embedded-opentype'),
         url('mavenprolight-200-webfont.woff2') format('woff2'),
         url('mavenprolight-200-webfont.woff') format('woff'),
         url('mavenprolight-200-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;

}


text:
// File System.Windows.Documents.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Documents
{
  public delegate void GetPageRootCompletedEventHandler(Object sender, GetPageRootCompletedEventArgs e);

  public enum LogicalDirection
  {
    Backward = 0,
    Forward = 1,
  }

  public enum TextPointerContext
  {
    None = 0,
    Text = 1,
    EmbeddedElement = 2,
    ElementStart = 3,
    ElementEnd = 4,
  }
}


text:
import pytest

from testcontainers.core.container import DockerContainer
from testcontainers.core.waiting_utils import wait_for_logs

def test_raise_timeout():
    with pytest.raises(TimeoutError):
        with DockerContainer("alpine").with_command("sleep 2") as container:
            wait_for_logs(container, "Hello from Docker!", timeout=1e-3)

def test_wait_for_hello():
    with DockerContainer("hello-world") as container:
        wait_for_logs(container, "Hello from Docker!")

def test_can_get_logs():
    with DockerContainer("hello-world") as container:
        wait_for_logs(container, "Hello from Docker!")
        stdout, stderr = container.get_logs()
        assert stdout, 'There should be something on stdout'


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Woopsa
{
    public interface IWoopsaElementReadOnlyList<T> : IEnumerable, IEnumerable<T>
    {
        T this[string name] { get; }

        T ByName(string name);

        T ByNameOrNull(string name);

        bool Contains(string Name);

        bool Contains(T element);

        int Count { get; }

    }

    public abstract class WoopsaElement : IWoopsaElement, IDisposable
    {
        #region Constructors

        protected WoopsaElement(WoopsaContainer owner, string name)
        {
            Owner = owner;
            Name = name;
        }

        #endregion

        #region IWoopsaElement

        public WoopsaContainer Owner { get; }

        IWoopsaContainer IWoopsaElement.Owner => Owner;

        public string Name { get; }

        #endregion IWoopsaElement

        public bool IsDisposed => _isDisposed;

        #region IDisposable

        protected virtual void Dispose(bool disposing)
        {
            _isDisposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion IDisposable

        protected void CheckDisposed()
        {
            if (_isDisposed)
                throw new ObjectDisposedException(this.GetPath());
        }

        private bool _isDisposed;
    }

    public class WoopsaContainer : WoopsaElement, IWoopsaContainer
    {
        #region Constructors

        public WoopsaContainer(WoopsaContainer container, string name)
            : base(container, name)
        {
            Lock = new object();
            _items = new WoopsaElementList<WoopsaContainer>();
            if (Owner != null)
                Owner.Add(this);
        }

        #endregion

        #region Public

        public IWoopsaElementReadOnlyList<WoopsaContainer> Items
        {
            get
            {
                DoPopulate();
                return _items;
            }
        }
        IEnumerable<IWoopsaContainer> IWoopsaContainer.Items => Items;

        public WoopsaContainer ByNameOrNull(string name)
        {
            return Items.ByNameOrNull(name);
        }

        public WoopsaContainer ByName(string name)
        {
            WoopsaContainer result;
            lock (Lock)
                result = ByNameOrNull(name);
            if (result != null)
                return result;
            else
                throw new WoopsaNotFoundException(string.Format("Woopsa element not found : {0}", name));
        }

        #endregion

        protected virtual void PopulateContainer(WoopsaElementList<WoopsaContainer> items)
        { }

        protected void DoPopulate()
        {
            CheckDisposed();
            lock (Lock)
            {
                if (!_populated)
                {
                    PopulateContainer(_items);
                    _populated = true;
                }
                else
                    UpdateItems();
            }
        }

        /// <summary>
        /// This method give the opportunity to update items, when the list of contained Items may change dynamically
        /// Typical usage is when publishing a list.
        /// This method is called every time Items are requested
        /// </summary>
        protected virtual void UpdateItems()
        {
        }

        #region Items Management Add / Remove / Clear

        internal void Add(WoopsaContainer item)
        {
            lock (Lock)
            {
                if (_items.ByNameOrNull(item.Name) != null)
                    throw new WoopsaException("Tried to add an item with duplicate name '" + item.Name + "' to WoopsaContainer '" + Name + "'");
                _items.Add(item);
            }
        }

        internal void Remove(WoopsaContainer item)
        {
            lock (Lock)
                _items.Remove(item);
        }

        protected virtual void Clear()
        {
            lock (Lock)
            {
                DisposeWoopsaElements(_items);
                _populated = false;
            }
        }

        internal void DisposeWoopsaElements(IEnumerable<WoopsaElement> elements)
        {
            var items = elements.ToArray();
            foreach (var item in items)
                item.Dispose();
        }

        #endregion

        #region IDisposable

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Clear();
                if (Owner != null)
                    Owner.Remove(this);
            }
            base.Dispose(disposing);
        }

        #endregion

        internal object Lock { get; }

        #region Private Members

        private readonly WoopsaElementList<WoopsaContainer> _items;
        private bool _populated;

        #endregion
    }

    public delegate WoopsaValue WoopsaPropertyGet(IWoopsaProperty property);
    public delegate void WoopsaPropertySet(IWoopsaProperty property, IWoopsaValue value);

    public class WoopsaProperty : WoopsaElement, IWoopsaProperty
    {
        #region Constructors

        public WoopsaProperty(WoopsaObject container, string name, WoopsaValueType type, WoopsaPropertyGet get, WoopsaPropertySet set)
            : base(container, name)
        {
            Type = type;
            _get = get;
            IsReadOnly = set == null;
            if (!IsReadOnly)
                _set = set;
            if (container != null)
                container.Add(this);
        }

        public WoopsaProperty(WoopsaObject container, string name, WoopsaValueType type, WoopsaPropertyGet get)
            : this(container, name, type, get, null)
        {
        }

        #endregion

        #region IWoopsaProperty

        public bool IsReadOnly { get; }

        public WoopsaValue Value
        {
            get
            {
                CheckDisposed();
                return _get(this);
            }
            set
            {
                ((IWoopsaProperty)this).Value = value;
            }
        }

        IWoopsaValue IWoopsaProperty.Value
        {
            get => Value;
            set
            {
                CheckDisposed();
                if (!IsReadOnly)
                    _set(this, value);
                else
                    throw new WoopsaException(string.Format("Cannot set read-only property {0}", Name));
            }
        }

        public WoopsaValueType Type { get; }

        #endregion IWoopsaProperty

        #region IDisposable

        protected override void Dispose(bool disposing)
        {
            if (Owner != null)
                ((WoopsaObject)Owner).Remove(this);
            base.Dispose(disposing);
        }

        #endregion

        #region Private Members

        private readonly WoopsaPropertyGet _get;
        private readonly WoopsaPropertySet _set;

        #endregion
    }

    public class WoopsaMethodArgumentInfo : IWoopsaMethodArgumentInfo
    {
        #region Constructor

        public WoopsaMethodArgumentInfo(string name, WoopsaValueType type)
        {
            Name = name;
            Type = type;
        }

        #endregion

        #region Public Properties

        public string Name { get; }

        public WoopsaValueType Type { get; }

        #endregion
    }

    public delegate WoopsaValue WoopsaMethodInvoke(IWoopsaValue[] arguments);

    public class WoopsaMethod : WoopsaElement, IWoopsaMethod
    {
        #region Constructors

        public WoopsaMethod(WoopsaObject container, string name, WoopsaValueType returnType, IEnumerable<WoopsaMethodArgumentInfo> argumentInfos, WoopsaMethodInvoke methodInvoke)
            : base(container, name)
        {
            ReturnType = returnType;
            ArgumentInfos = argumentInfos;
            _methodInvoke = methodInvoke;
            if (container != null)
                container.Add(this);
        }

        #endregion

        #region IWoopsaMethod

        public WoopsaValue Invoke(params WoopsaValue[] arguments)
        {
            CheckDisposed();
            return _methodInvoke(arguments);
        }
        public WoopsaValue Invoke(IEnumerable<IWoopsaValue> arguments)
        {
            CheckDisposed();
            return _methodInvoke(arguments.ToArray());
        }

        IWoopsaValue IWoopsaMethod.Invoke(IWoopsaValue[] arguments)
        {
            return Invoke(arguments);
        }

        public WoopsaValueType ReturnType { get; }

        public IEnumerable<IWoopsaMethodArgumentInfo> ArgumentInfos { get; }

        #endregion IWoopsaMethod

        #region IDisposable

        protected override void Dispose(bool disposing)
        {
            if (Owner != null)
                ((WoopsaObject)Owner).Remove(this);
            base.Dispose(disposing);
        }

        #endregion

        #region Private Members

        private readonly WoopsaMethodInvoke _methodInvoke;

        #endregion
    }

    public class WoopsaObject : WoopsaContainer, IWoopsaObject
    {
        #region Constructors

        public WoopsaObject(WoopsaContainer container, string name)
            : base(container, name)
        {
            _properties = new WoopsaElementList<WoopsaProperty>();
            _methods = new WoopsaElementList<WoopsaMethod>();
        }

        #endregion

        #region IWoopsaObject Properties

        public IWoopsaElementReadOnlyList<WoopsaProperty> Properties
        {
            get
            {
                lock (Lock)
                {
                    DoPopulate();
                    return _properties;
                }
            }
        }

        IEnumerable<IWoopsaProperty> IWoopsaObject.Properties => Properties;

        public IWoopsaElementReadOnlyList<WoopsaMethod> Methods
        {
            get
            {
                lock (Lock)
                {
                    DoPopulate();
                    return _methods;
                }
            }
        }

        IEnumerable<IWoopsaMethod> IWoopsaObject.Methods => Methods;

        #endregion

        public new WoopsaElement ByNameOrNull(string name)
        {
            WoopsaElement result;
            lock (Lock)
            {
                result = base.ByNameOrNull(name);
                if (result == null)
                    result = Properties.ByNameOrNull(name);
                if (result == null)
                    result = Methods.ByNameOrNull(name);
            }
            return result;
        }

        public new WoopsaElement ByName(string name)
        {
            WoopsaElement result = ByNameOrNull(name);
            if (result != null)
                return result;
            else
                throw new WoopsaNotFoundException(string.Format("Woopsa element not found : {0}", name));
        }

        protected override void PopulateContainer(WoopsaElementList<WoopsaContainer> items)
        {
            base.PopulateContainer(items);
            PopulateObject();
        }

        protected virtual void PopulateObject()
        {
        }

        #region Properties Management Add / Remove / Clear

        internal void Add(WoopsaProperty item)
        {
            if (_properties.ByNameOrNull(item.Name) != null)
                throw new WoopsaException("Tried to add a property with duplicate name '" + item.Name + "' to WoopsaObject '" + Name + "'");
            _properties.Add(item);
        }

        internal void Remove(WoopsaProperty item)
        {
            _properties.Remove(item);
        }

        #endregion

        #region Methods Management Add / Remove / Clear

        internal void Add(WoopsaMethod item)
        {
            lock (Lock)
            {
                if (_methods.ByNameOrNull(item.Name) != null)
                    throw new WoopsaException("Tried to add a method with duplicate name '" + item.Name + "' to WoopsaObject '" + Name + "'");
                _methods.Add(item);
            }
        }

        internal void Remove(WoopsaMethod item)
        {
            lock (Lock)
                _methods.Remove(item);
        }

        protected override void Clear()
        {
            lock (Lock)
            {
                DisposeWoopsaElements(_properties);
                DisposeWoopsaElements(_methods);
                base.Clear();
            }
        }

        #endregion

        #region Private Members

        private readonly WoopsaElementList<WoopsaProperty> _properties;
        private readonly WoopsaElementList<WoopsaMethod> _methods;

        #endregion
    }

    public class WoopsaRoot : WoopsaContainer
    {
        public WoopsaRoot()
            : base(null, string.Empty)
        {
        }
    }

    public class WoopsaElementList<T> : IWoopsaElementReadOnlyList<T> where T : WoopsaElement
    {
        public WoopsaElementList()
        {
            _itemsByName = new Dictionary<string, T>();
        }

        public T this[string name]
        {
            get
            {
                lock (_itemsByName)
                    return _itemsByName[name];
            }
        }

        public int Count
        {
            get
            {
                lock (_itemsByName)
                    return _itemsByName.Count;
            }
        }

        public IEnumerator<T> GetEnumerator()
        {
            lock (_itemsByName)
            {
                // TODO : thread safety
                return _itemsByName.Values.GetEnumerator();
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            // TODO : thread safety
            lock (_itemsByName)
                return _itemsByName.Values.GetEnumerator();
        }

        public void Add(T item)
        {
            lock (_itemsByName)
                _itemsByName.Add(item.Name, item);
        }

        public void Remove(T item)
        {
            lock (_itemsByName)
                _itemsByName.Remove(item.Name);
        }

        public bool Contains(string key)
        {
            lock (_itemsByName)
                return _itemsByName.ContainsKey(key);
        }

        public bool Contains(T element)
        {
            lock (_itemsByName)
                return _itemsByName.ContainsValue(element);
        }

        public void Clear()
        {
            T[] items;
            lock (_itemsByName)
                items = _itemsByName.Values.ToArray();
            foreach (var item in items)
                item.Dispose();
        }

        public T ByName(string name)
        {
            lock (_itemsByName)
                return _itemsByName[name];
        }

        public T ByNameOrNull(string name)
        {
            lock (_itemsByName)
            {
                if (Contains(name))
                    return ByName(name);
                else
                    return null;
            }
        }

        private Dictionary<string, T> _itemsByName;

    }
}


text:
FROM vertx/vertx3

ENV VERTICLE_FILE vert.groovy
ENV VERTICLE_HOME /usr/verticles

COPY $VERTICLE_FILE $VERTICLE_HOME/

WORKDIR $VERTICLE_HOME

ENTRYPOINT ["sh", "-c"]
CMD ["vertx run $VERTICLE_FILE --cluster"]


text:
<?php

  /**
   * BaseDocumentCategory class
   */
  class BaseDocumentCategory extends ApplicationObject {

    /**
     * All table fields
     *
     * @var array
     */
    var $fields = array('id', 'name');

    /**
     * Primary key fields
     *
     * @var array
     */
    var $primary_key = array('id');

    /**
     * Name of AI field (if any)
     *
     * @var string
     */
    var $auto_increment = 'id';

    /**
     * Construct the object and if $id is present load record from database
     *
     * @param mixed $id
     * @return DocumentCategory
     */
    function __construct($id = null) {
      $this->table_name = TABLE_PREFIX . 'document_categories';
      parent::__construct($id);
    }

    /**
     * Return value of id field
     *
     * @param void
     * @return integer
     */
    function getId() {
      return $this->getFieldValue('id');
    }

    /**
     * Set value of id field
     *
     * @param integer $value
     * @return integer
     */
    function setId($value) {
      return $this->setFieldValue('id', $value);
    }

    /**
     * Return value of name field
     *
     * @param void
     * @return string
     */
    function getName() {
      return $this->getFieldValue('name');
    }

    /**
     * Set value of name field
     *
     * @param string $value
     * @return string
     */
    function setName($value) {
      return $this->setFieldValue('name', $value);
    }

    /**
     * Set value of specific field
     *
     * @param string $name
     * @param mided $value
     * @return mixed
     */
    function setFieldValue($name, $value) {
      $real_name = $this->realFieldName($name);

      $set = $value;
      switch($real_name) {
        case 'id':
          $set = intval($value);
          break;
        case 'name':
          $set = strval($value);
          break;
      } // switch
      return parent::setFieldValue($real_name, $set);
    } // switch

  }

?>


text:
CREATE TABLE party
(
      id            $PARTY_ID_TYPE            NOT NULL
    , name          $PARTY_NAME_TYPE          NOT NULL
    , password_hash $PARTY_PASSWORD_HASH_TYPE NOT NULL
    , category_id   $PARTY_CATEGORY_ID_TYPE   NOT NULL
    , CONSTRAINT uk_party_name
        UNIQUE KEY (name)
    , CONSTRAINT fk_party_category_id
        FOREIGN KEY (category_id) REFERENCES party_category (id)
            ON DELETE RESTRICT
            ON UPDATE CASCADE
    , CONSTRAINT pk_party
        PRIMARY KEY (id)
) ENGINE=InnoDB
;


text:
package uk.co.markberridge.users.dao;

import java.util.Map;

import uk.co.markberridge.users.UserAlreadyExistsException;
import uk.co.markberridge.users.domain.User;
import uk.co.markberridge.users.domain.User.UserBuilder;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

public class UserDaoInMemory implements UserDao {

    private final Map<String, User> users = Maps.newConcurrentMap();

    public UserDaoInMemory() {
        createUser(new UserBuilder().username("admin").build());
    }

    public Optional<User> getUserByUsername(String username) {
        return Optional.fromNullable(users.get(username));
    }

    public User createUser(User user) throws UserAlreadyExistsException {
        Preconditions.checkNotNull(user);
        if (users.get(user.getUsername()) != null) {
            throw new UserAlreadyExistsException(user.getUsername());
        }
        return createOrUpdateUser(user);
    }

    public User createOrUpdateUser(User user) {
        Preconditions.checkNotNull(user);
        users.put(user.getUsername(), user);
        return user;
    }

    public boolean deleteUserByUsername(String userId) {
        return users.remove(userId) != null;
    }
}


text:
layout: post
title: Week 13
---

1. What did you do this past week?

    This past week, we discussed clone, virtual methods and abstract classes. Also, guest speakers from Spiceworks came to talk to us about their company. I'd say the most unique thing they mentioned in their presentation were stock options. I had no idea what they were before their talk. But, they didn't really explain what they were.

    I also finished the last project. We had to write nearly 80 unit tests. It's ideal to have unit tests written first or at least, at the same time a method is completed, but it's hard to do when starting off with a blank slate. I also find it hard to switch gears from being in the zone of implementing logic to testing it out. Luckily, our bugs weren't too hard to find.

2. What's in your way?

    In my way now is my other class. For the majority of the semester, this class took priority over my other class because of the projects every other week. However, there is a project deadline and presentation in the other class, so it's hard for me to take some time to study when I could be working on the project.

3. What will you do next week?

    This week, there will only be one class and then the rest of the week is off for Thanksgiving holidays. And then the week after is the exam! I really hope that I'll be productive by studying for the exam and possibly doing the extra credit assignment.

**Tip of the week:** This [article](https://medium.freecodecamp.com/the-code-im-still-ashamed-of-e4c021dff55e#.e1yk7l5ry) is about a person who helped build a website for a pharmaceutical company that was under the guise of a general information site when really it was an advertisement for their drug. It's an important reminder that there are serious consequences to our work and that we should always question if what we're being asked to do is ethical.


text:
package com.github.srgg.yads.impl;

import com.github.srgg.yads.api.ActivationAware;
import com.github.srgg.yads.impl.api.context.Subscribe;
import com.github.srgg.yads.api.Configurable;
import com.github.srgg.yads.api.message.Messages;
import com.github.srgg.yads.impl.api.context.ExecutionContext;
import com.github.srgg.yads.impl.util.TaggedLogger;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergey Galkin <srggal at gmail dot com>
 */
public abstract class AbstractNode<C extends ExecutionContext> implements ActivationAware, Configurable<C> {
    private final Logger logger;

    private final String nodeId;

    private C context;
    private final Messages.NodeType nodeType;

    protected AbstractNode(final String id, final Messages.NodeType type) {
        this.nodeId = id;
        this.nodeType = type;
        logger = new TaggedLogger(LoggerFactory.getLogger(getClass()), String.format("Node '%s': ", id));
    }

    protected final Logger logger() {
        return logger;
    }

    protected final C context() {
        return context;
    }

    public final Messages.NodeType getNodeType() {
        return nodeType;
    }

    @Override
    public final String getId() {
        return nodeId;
    }

    @Override
    public final void start() {
        logger().debug("is about to start");
        doStart();
        setState(State.STARTED.name());
        logger().info("has been STARTED");
    }

    @Override
    public final void stop() {
        logger().debug("is about to stop");
        setState(State.STOPPED.name());
        doStop();
        logger().info("has been STOPPED");
    }

    protected void doStart() {
    }

    protected void doStop() {
    }

    @Override
    public void configure(final C ctx) throws Exception {
        this.context = ctx;
        logger().debug("Configured");
    }

    @Subscribe
    public void onStateChanged(final String old, final String current) {
        logger().debug("[STATE] changed '{}' -> '{}'", old, current);
    }

    /**
     * DO NOT CALL THIS METHOD DIRECTLY.
     *
     * <p/>
     * It was introduced because of lack of proper visibility support in Java, as a result
     * AbstractNodeRuntime being placed in the separate package can access the only public methods :(
     * (later it might be refactored by using Factories and other Java patterns that hides such visibility issues)
     */
    @VisibleForTesting
    public final String setState(final String newState) throws IllegalStateException {
        return context().changeState(newState);
    }

    @Override
    public String getState() {
        return context().getState();
    }
}


text:
/*
 * 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.facebook.presto.operator.aggregation;

import com.facebook.presto.byteCode.DynamicClassLoader;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteStreams;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

public final class IsolatedClass
{
    private IsolatedClass() {}

    public static <T> Class<? extends T> isolateClass(Class<T> publicBaseClass, Class<? extends T> implementationClass, Class<?>... additionalClasses)
    {
        DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(publicBaseClass.getClassLoader());

        ImmutableMap.Builder<String, byte[]> builder = ImmutableMap.builder();
        builder.put(implementationClass.getName(), getByteCode(implementationClass));
        for (Class<?> additionalClass : additionalClasses) {
            builder.put(additionalClass.getName(), getByteCode(additionalClass));
        }

        // load classes into a private class loader
        Map<String, Class<?>> isolatedClasses = dynamicClassLoader.defineClasses(builder.build());
        Class<?> isolatedClass = isolatedClasses.get(implementationClass.getName());

        // verify the isolated class
        checkArgument(isolatedClass != null, "Could load class %s", implementationClass.getName());
        checkArgument(publicBaseClass.isAssignableFrom(isolatedClass),
                "Error isolating class %s, newly loaded class is not a sub type of %s",
                implementationClass.getName(),
                publicBaseClass.getName());
        checkState(isolatedClass != implementationClass, "Isolation failed");

        return isolatedClass.asSubclass(publicBaseClass);
    }

    private static byte[] getByteCode(Class<?> clazz)
    {
        InputStream stream = clazz.getClassLoader().getResourceAsStream(clazz.getName().replace('.', '/') + ".class");
        checkArgument(stream != null, "Could not obtain byte code for class %s", clazz.getName());
        try {
            return ByteStreams.toByteArray(stream);
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
}


text:
require 'spec_helper'
module Exlibris
  module Nyu
    module Aleph
      describe CallNumber do
        let(:classification) { "classification" }
        let(:description) { "description" }
        let(:item_call_number) { Exlibris::Aleph::Item::CallNumber.new(classification, description)}
        subject(:call_number) { CallNumber.new(item_call_number) }
        it { should be_a CallNumber}
        describe '#classification' do
          subject { call_number.classification }
          it { should eq "classification" }
        end
        describe '#description' do
          subject { call_number.description }
          it { should eq "description" }
        end
        describe '#to_s' do
          subject { call_number.to_s }
          context 'when initialized with a classification' do
            let(:classification) { "classification" }
            context 'and initialized with a description' do
              let(:description) { "description" }
              it { should eq "(classification description)" }
              context 'and the classification has a  ' do
                let(:classification) { "classification classification" }
                it { should eq "(classification classification description)" }
              end
              context 'and the classification has some MARC' do
                let(:classification) { "classification$$iclassification$$h" }
                it { should eq "(classification classification description)" }
              end
              context 'and the description has a  ' do
                let(:description) { "description description" }
                it { should eq "(classification description description)" }
              end
            end
            context 'and initialized without a description' do
              let(:description) { nil }
              it { should eq "(classification)"}
            end
          end
          context 'when initialized with an item call number argument which is not an Exlibris::Aleph::Item::CallNumber' do
            let(:item_call_number) { 'invalid' }
            it 'should raise an ArgumentError' do
              expect { subject }.to raise_error ArgumentError
            end
          end
        end
      end
    end
  end
end


text:
'use strict';

var globalTimers = require('timers');

function LagSampler(opts) {
    this.ringpop = opts.ringpop;
    this.timers = opts.timers || globalTimers;
    this.lagTimer = null;
    this.currentLag = 0;

    // toobusy auto-starts sampling. lazily-require until started.
    this.toobusy = null;
}

LagSampler.prototype.start = function start() {
    var self = this;

    if (this.lagTimer) {
        this.ringpop.logger.debug('ringpop lag sampler lag timer already started', {
            local: this.ringpop.whoami()
        });
        return;
    }

    if (!this.toobusy) {
        this.toobusy = require('toobusy-js');
    }

    schedule();
    this.ringpop.logger.debug('ringpop lag sampler started', {
        local: this.ringpop.whoami()
    });

    function schedule() {
        self.lagTimer = self.timers.setTimeout(function onTimeout() {
            self.currentLag = self.toobusy.lag();
            schedule();
        }, self.ringpop.config.get('lagSamplerInterval'));
    }
};

LagSampler.prototype.stop = function stop() {
    if (!this.lagTimer) {
        this.ringpop.logger.debug('ringpop lag sampler lag timer already stopped', {
            local: this.ringpop.whoami()
        });
        return;
    }

    this.timers.clearTimeout(this.lagTimer);
    this.lagTimer = null;
    this.ringpop.logger.debug('ringpop lag sampler stopped', {
        local: this.ringpop.whoami()
    });

    if (this.toobusy) {
        this.toobusy.shutdown();
        this.toobusy = null;
    }
};

module.exports = LagSampler;


text:
<?php

namespace SiteBDE\HomePageBundle\Repository;

/**
 * PageTypeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PageTypeRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Email Testing</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Email Testing

Experiment to avoid writing "@" and "mailto" on websites, causes spam, but still keep the click to email functionality

Standard

				patpaskoch@gmail.com

JavaScript

patpaskoch@gmail.com

Render the Email with js

JavaScript 2te Version

patpaskoch@gmail.com

weder ein @ noch ein mailto im code und ist clickbar

HTML Commentare

				patpaskoch@gmail.com
				Tryed to implenent html comments into Email,....not working to klick.


text:
package com.netflix.spinnaker.clouddriver.yandex.deploy.ops;

import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperation;
import com.netflix.spinnaker.clouddriver.yandex.deploy.description.ResizeYandexServerGroupDescription;
import com.netflix.spinnaker.clouddriver.yandex.model.YandexCloudServerGroup;
import com.netflix.spinnaker.clouddriver.yandex.service.YandexCloudFacade;
import java.util.List;

public class ResizeYandexServerGroupAtomicOperation
    extends AbstractYandexAtomicOperation<ResizeYandexServerGroupDescription>
    implements AtomicOperation<Void> {

  public static final String BASE_PHASE = YandexCloudFacade.RESIZE_SERVER_GROUP;

  public ResizeYandexServerGroupAtomicOperation(ResizeYandexServerGroupDescription description) {
    super(description);
  }

  @Override
  public Void operate(List<Void> priorOutputs) {
    String serverGroupName = description.getServerGroupName();
    status(BASE_PHASE, "Initializing resize of server group '%s'...", serverGroupName);
    YandexCloudServerGroup serverGroup = getServerGroup(BASE_PHASE, serverGroupName);
    yandexCloudFacade.resizeServerGroup(
        credentials, serverGroup.getId(), description.getCapacity().getDesired());
    status(BASE_PHASE, "Done resizing server group '%s'.", serverGroupName);
    return null;
  }
}


text:
/*
    -- clMAGMA (version 1.1.0) --
       Univ. of Tennessee, Knoxville
       Univ. of California, Berkeley
       Univ. of Colorado, Denver
       @date January 2014

       @generated from zpotrs_gpu.cpp normal z -> d, Fri Jan 10 15:51:17 2014
*/

#include <stdio.h>
#include "common_magma.h"

extern "C" magma_err_t
magma_dpotrs_gpu(magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs,
                 magmaDouble_ptr dA, size_t dA_offset, magma_int_t ldda,
                 magmaDouble_ptr dB, size_t dB_offset, magma_int_t lddb,
                 magma_err_t *info, magma_queue_t queue )
{
/*  -- clMagma (version 0.1) --
       Univ. of Tennessee, Knoxville
       Univ. of California, Berkeley
       Univ. of Colorado, Denver
       @date January 2014

    Purpose
    =======

    DPOTRS solves a system of linear equations A*X = B with a symmetric
    positive definite matrix A using the Cholesky factorization
    A = U**T*U or A = L*L**T computed by DPOTRF.

    Arguments
    =========

    UPLO    (input) CHARACTER*1
            = 'U':  Upper triangle of A is stored;
            = 'L':  Lower triangle of A is stored.

    N       (input) INTEGER
            The order of the matrix A.  N >= 0.

    NRHS    (input) INTEGER
            The number of right hand sides, i.e., the number of columns
            of the matrix B.  NRHS >= 0.

    dA      (input) DOUBLE_PRECISION array on the GPU, dimension (LDDA,N)
            The triangular factor U or L from the Cholesky factorization
            A = U**T*U or A = L*L**T, as computed by DPOTRF.

    LDDA    (input) INTEGER
            The leading dimension of the array A.  LDDA >= max(1,N).

    dB      (input/output) DOUBLE_PRECISION array on the GPU, dimension (LDDB,NRHS)
            On entry, the right hand side matrix B.
            On exit, the solution matrix X.

    LDDB    (input) INTEGER
            The leading dimension of the array B.  LDDB >= max(1,N).

    INFO    (output) INTEGER
            = 0:  successful exit
            < 0:  if INFO = -i, the i-th argument had an illegal value
    =====================================================================   */

    double z_one = MAGMA_D_MAKE(  1.0, 0.0 );

    *info = 0 ;
    if( (uplo != MagmaUpper) && (uplo != MagmaLower) )
        *info = -1;
    if( n < 0 )
        *info = -2;
    if( nrhs < 0)
        *info = -3;
    if ( ldda < max(1, n) )
        *info = -5;
    if ( lddb < max(1, n) )
        *info = -7;
    if (*info != 0) {
        magma_xerbla( __func__, -(*info) );
        return *info;
    }

    /* Quick return if possible */
    if ( (n == 0) || (nrhs == 0) ) {
        return *info;
    }

    if( uplo== MagmaUpper){
        if ( nrhs == 1) {
            chk(magma_dtrsv(MagmaUpper, MagmaTrans, MagmaNonUnit, n, dA, dA_offset, ldda, dB, dB_offset, 1, queue));
            chk(magma_dtrsv(MagmaUpper, MagmaNoTrans,   MagmaNonUnit, n, dA, dA_offset, ldda, dB, dB_offset, 1, queue));
        } else {
            chk(magma_dtrsm(MagmaLeft, MagmaUpper, MagmaTrans, MagmaNonUnit, n, nrhs, z_one, dA, dA_offset, ldda, dB, dB_offset, lddb, queue));
            chk(magma_dtrsm(MagmaLeft, MagmaUpper, MagmaNoTrans,   MagmaNonUnit, n, nrhs, z_one, dA, dA_offset, ldda, dB, dB_offset, lddb, queue));
        }
    }
    else{
        if ( nrhs == 1) {
            chk(magma_dtrsv(MagmaLower, MagmaNoTrans,   MagmaNonUnit, n, dA, dA_offset, ldda, dB, dB_offset, 1, queue ));
            chk(magma_dtrsv(MagmaLower, MagmaTrans, MagmaNonUnit, n, dA, dA_offset, ldda, dB, dB_offset, 1, queue ));
        } else {
            chk(magma_dtrsm(MagmaLeft, MagmaLower, MagmaNoTrans,   MagmaNonUnit, n, nrhs, z_one, dA, dA_offset, ldda, dB, dB_offset, lddb, queue));
            chk(magma_dtrsm(MagmaLeft, MagmaLower, MagmaTrans, MagmaNonUnit, n, nrhs, z_one, dA, dA_offset, ldda, dB, dB_offset, lddb, queue));
        }
    }
    chk( magma_queue_sync( queue ));
    return *info;
}


text:
package fredboat.command.fun;

import fredboat.commandmeta.abs.Command;
import fredboat.commandmeta.abs.CommandContext;
import fredboat.commandmeta.abs.IFunCommand;
import fredboat.messaging.internal.Context;
import fredboat.util.rest.Http;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;

public class JokeCommand extends Command implements IFunCommand {

    private static final Logger log = LoggerFactory.getLogger(JokeCommand.class);

    public JokeCommand(String name, String... aliases) {
        super(name, aliases);
    }

    @Override
    public void onInvoke(@Nonnull CommandContext context) {
        try {
            JSONObject object = Http.get("http://api.icndb.com/jokes/random").asJson();

            if (!"success".equals(object.getString("type"))) {
                throw new RuntimeException("Couldn't gather joke ;|");
            }

            String joke = object.getJSONObject("value").getString("joke");

            if (!context.getMentionedUsers().isEmpty()) {
                joke = joke.replaceAll("Chuck Norris", context.getMentionedUsers().get(0).getAsMention());
            } else if (context.hasArguments()) {
                joke = joke.replaceAll("Chuck Norris", context.rawArgs);
            }

            joke = joke.replaceAll(""", "\"");

            context.reply(joke);
        } catch (IOException | JSONException e) {
            log.error("Failed to fetch joke", e);
            context.reply(context.i18n("Please try again later."));//todo i18n a generic try again error message for api dependent commands
        }
    }

    @Nonnull
    @Override
    public String help(@Nonnull Context context) {
        return "{0}{1} @<username>\n#Tell a joke about a user.";
    }
}


text:
<!DOCTYPE html>

    <title>submergence:Reply#event(content documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../../../highlight.css" />

            argument

                :submergence.Reply#event(content

Any number of additional arguments containing JSON-serializable data to ship as arguments to the
triggered event.

Any number of additional arguments containing JSON-serializable data to ship as arguments to the
triggered event.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
layout: post
title: How to send Telegram Messages from PowerShell script
subtitle: Using the WhatsMate Telegram Gateway REST API
published: true
last_modified_at: 2022-06-16T00:00:00+08:00
---

This article shows you how to send a Telegram message from a PowerShell script.

Before the recipient can receive your Telegram message, she will need to register with the WhatsMate Telegram Gateway. Instructions are available on the [official site](https://www.whatsmate.net/telegram-gateway-api.html). *Unregistered users will never receive messages from the Gateway.*

To send a Telegram message from a PowerShell script, do this:

1. Copy the following source code to your PowerShell script.
2. Customize the TODO lines:
   * Specify your gateway instance ID on line 4.
   * Specify your client ID and secret on lines 5 and 6.
   * Specify your target recipient on line 1. Remember to include the country code.
   * Specify your message on line 2.
3. Run the script in PowerShell to send your message: `.\send-telegram-text.ps1`

You will need a trial account to call the above API. Go [sign up](https://www.whatsmate.net/telegram-gateway-api.html) now.


text:
/**
 * Base class for test cases which are using Sikuli. This is still experimental. It relies on the RobotApplet, which, by
 * default, is not distributed with Aria Templates.
 * @private
 */
Aria.classDefinition({
    $classpath : 'aria.jsunit.SikuliTestCase',
    $extends : 'aria.jsunit.TestCase',
    $dependencies : ['aria.jsunit.RobotJavaApplet'],
    $statics : {
        /**
         * Settings to run test cases.
         * @type Object
         */
        settings : {
            /**
             * Path to the executable of the browser currently being tested. It should contain the string %url% to be
             * replaced by the url to load in the browser.
             * @type String
             */
            browserPath : ""
        },

        FAILED_OPENING_BROWSER : "The browser could not be opened. Command line used: %1"
    },
    $constructor : function () {
        this.$TestCase.constructor.call(this);
        /**
         * Directory containing images. By default, it corresponds to the directory containing the test case.
         * @type String
         */
        this.imagesRoot = aria.core.DownloadMgr.resolveURL(this.$package.replace(/\./g, "/", true)) + "/";

        /**
         * Reference to the RobotJavaApplet object.
         */
        this.robot = null;

        /**
         * Reference to a Java Screen object from Sikuli (see the JavaDoc here)
         */
        this.screen = null;

        /**
         * Reference to the Java KeyModifier class from Sikuli (see the JavaDoc here)
         */
        this.KeyModifier = null;

        /**
         * Reference to the Java Key class from Sikuli (see the JavaDoc here)
         */
        this.Key = null;

    },
    $destructor : function () {
        this.robot = null;
        this.screen = null;
        this.KeyModifier = null;
        this.Key = null;
        this.$TestCase.$destructor.call(this);
    },
    $prototype : {
        /**
         * Entry point for the Sikuli test.
         */
        testAsyncRunSikuliTest : function () {
            aria.jsunit.RobotJavaApplet.initRobot({
                fn : this._robotStarted,
                scope : this
            });
        },

        /**
         * Initializes the robot, screen, KeyModifier and Key properties and calls runSikuliTest. This method is called
         * automatically from testAsyncRunSikuli once the robot applet is initialized.
         */
        _robotStarted : function () {
            this.robot = aria.jsunit.RobotJavaApplet.applet;
            this.screen = this.robot.createSikuliScreen();
            this.KeyModifier = this.robot.Packages.org.sikuli.script.KeyModifier;
            this.Key = this.robot.Packages.org.sikuli.script.Key;
            try {
                this.runSikuliTest();
            } catch (e) {
                this.handleAsyncTestError(e);
            }
        },

        /**
         * Creates a pattern from an image file.
         * @param {String} imageName Path to the image file. It is relative to this.imagesRoot.
         * @return {Object} A Java Pattern object containing the image.
         */
        image : function (imageName) {
            return this.robot.createPattern(this.imagesRoot + imageName);
        },

        /**
         * Contains the actual test case. It is intended to be overridden by sub-classes. The method in the
         * SikuliTestCase base class only calls sikuliTestEnd.
         */
        runSikuliTest : function () {
            // to be overridden by sub-classes
            this.sikuliTestEnd();
        },

        /**
         * Notifies the framework that the test is finished. This method is intended to be called from runSikuliTest or
         * in the callback of a method called from runSikuliTest.
         */
        sikuliTestEnd : function () {
            this.notifyTestEnd("testAsyncRunSikuliTest");
        },

        /**
         * Opens a URL in the currently tested browser.
         * @param {String} url
         */
        openURL : function (url) {
            var browserPath = this.settings.browserPath;
            var cmdLine = browserPath.replace(/\%url\%/, url);
            var app = this.robot.createApp(cmdLine);
            var res = app.open();
            if (res == null) {
                this.$logError(this.FAILED_OPENING_BROWSER, [cmdLine]);
                return false;
            }
            return true;
        }
    }
});


text:
/**
 * @author Charlie Fontana <charlie@ambisafe.co>
 * @date 10/07/2015
 */

#import <Foundation/Foundation.h>
#import "AmbisafeTransaction.h"

@interface AmbisafeAccount : NSObject

@property (nonatomic, copy) NSString *key;
@property (nonatomic, copy) NSString *currency;
@property (nonatomic, copy) NSString *data;
@property (nonatomic, copy) NSString *iv;
@property (nonatomic, copy) NSString *salt;
@property (nonatomic, copy) NSString *publicKey;
@property (nonatomic, copy) NSString *privateKey;
@property (nonatomic, copy) NSString *password;

/*!
 * Defines the Account constructor based on a container and a password.
 *
 * \param {NSDictionary} container.
 * \param {NSString} password.
 * \return none.
 */
- (AmbisafeAccount *)initWithContainer:(NSDictionary *)container password:(NSString *)password;

/*!
 * Instance method that signs a transaction.
 *
 * \param {AmbisafeTransaction} tx unsigned transaction: {hex:'...', fee:'...', sighashes:['...', '...']}.
 * \return {AmbisafeTransaction} signed transaction.
 */
- (AmbisafeTransaction *)signTransaction:(AmbisafeTransaction *)tx;

/*!
 * Instance method that set a new password
 *
 * \param {NSString} password
 * \return none.
 */
- (NSString *)setNewPassword:(NSString *)password;

/*!
 * Instance method that returns the Account's data in a JSON format
 *
 * \return {NSString} return the account data as NSString.
 */
- (NSString *)stringify;

/*!
 * Instance method that parse the Account's data
 *
 * \param {NSString} data return the account data as NSString
 * \return none.
 */
- (NSString *)parse:(NSString *)data;

/*!
 * Instance method that get the Account's container as a NSObject
 *
 * \return {NSObject}
 */
- (NSObject *)getContainer;

/*!
 * Instance method that get the Account's container as NSString
 *
 * \return {NSString}
 */
- (NSString *)getStringContainer;

@end


text:
package folderTreeView;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.Alert;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.TreeCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class FilePathTreeCell extends TreeCell<String> {
    private TextField fileName;
    private ContextMenu folderContextMenu;

    public FilePathTreeCell() {
        initializeContextMenu();
    }

    private void initializeContextMenu() {
        folderContextMenu = new ContextMenu();
        MenuItem addNewFileMenuItem = new MenuItem("New file");
        MenuItem addNewFolderMenuItem = new MenuItem("New folder");
        MenuItem deleteMenuItem = new MenuItem("Delete");
        folderContextMenu.getItems().addAll(addNewFileMenuItem, addNewFolderMenuItem, deleteMenuItem);
        addNewFileEventHandler(addNewFileMenuItem);
        addNewFolderEventHandler(addNewFolderMenuItem);
        addDeleteEventHandler(deleteMenuItem);
    }

    private void addNewFileEventHandler(MenuItem addNewFileMenuItem) {
        addNewFileMenuItem.setOnAction((ActionEvent event) -> {
            FilePathTreeItem selectedDirectory = (FilePathTreeItem) getTreeItem();
            if (selectedDirectory.isDirectory()) {
                Optional<String> result = createTextInputDialog("New file", "New file window", "Please enter the name of the new file");
                if (result.isPresent()) {
                    String fileName = result.get();
                    String directoryPath = selectedDirectory.getFullPath();
                    Path path = Paths.get(directoryPath, fileName);
                    if (!Files.exists(path)) {
                        createNewFile(path);
                        FilePathTreeItem newFile = new FilePathTreeItem(path);
                        selectedDirectory.getChildren().add(newFile);
                    } else {
                        displayInformationDialog("File information", null, "File already exists!");
                    }
                }
            } else {
                displayInformationDialog("Wrong file", null, "File chosen is not a directory!");
            }
        });
    }

    private void createNewFile(Path path) {
        try {
            Files.createFile(path);
        } catch (IOException e) {
            displayInformationDialog("File creation error", "File creation error", "Error while creating new file " + e.getLocalizedMessage());
        }
    }

    private void addNewFolderEventHandler(MenuItem addNewFolderMenuItem) {
        addNewFolderMenuItem.setOnAction((ActionEvent event) -> {
            FilePathTreeItem selectedDirectory = (FilePathTreeItem) getTreeItem();
            if (selectedDirectory.isDirectory()) {
                Optional<String> result = createTextInputDialog("New folder", "New folder window", "Please enter the name of the new folder");
                if (result.isPresent()) {
                    String fileName = result.get();
                    String directoryPath = selectedDirectory.getFullPath();
                    Path path = Paths.get(directoryPath, fileName);
                    if (!Files.exists(path)) {
                        createNewFolder(path);
                        FilePathTreeItem newFile = new FilePathTreeItem(path);
                        selectedDirectory.getChildren().add(newFile);
                    } else {
                        displayInformationDialog("Folder information", null, "Folder already exists!");
                    }
                }
            } else {
                displayInformationDialog("Wrong file", null, "File chosen is not a directory!");
            }
        });
    }

    private void createNewFolder(Path path) {
        try {
            Files.createDirectory(path);
        } catch (IOException e) {
            displayInformationDialog("Folder creation error", "Folder creation error", "Error while creating new folder " + e.getLocalizedMessage());
        }
    }

    private void addDeleteEventHandler(MenuItem deleteMenuItem) {
        deleteMenuItem.setOnAction((ActionEvent event) -> {
            FilePathTreeItem treeItem = (FilePathTreeItem) getTreeItem();
            Path path = Paths.get(treeItem.getFullPath());
            try {
                Files.delete(path);
                treeItem.getParent().getChildren().removeAll(treeItem);
            } catch (IOException e) {
                displayInformationDialog("Delete error", "Error occurred when deleting" + path.toString(), e.getLocalizedMessage());
            }
        });
    }

    @Override
    public void startEdit() {
        super.startEdit();

        if (fileName == null) {
            initializeFileName();
        }
        setText(null);
        setGraphic(fileName);
        fileName.selectAll();
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getItem());
        setGraphic(getTreeItem().getGraphic());
    }

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (fileName != null) {
                    fileName.setText(getFileName());
                }
                setText(null);
                setGraphic(fileName);
            } else {
                setText(getFileName());
                setGraphic(getTreeItem().getGraphic());
                setFolderContextMenu();
            }
        }
    }

    private void setFolderContextMenu() {
        if (getTreeItem() instanceof FilePathTreeItem) {
            FilePathTreeItem treeItem = (FilePathTreeItem) getTreeItem();
            if (treeItem.isDirectory()) {
                setContextMenu(folderContextMenu);
            }
        }
    }

    private void initializeFileName() {
        fileName = new TextField(getFileName());
        fileName.setOnKeyReleased((KeyEvent event) -> {
            if (event.getCode() == KeyCode.ENTER) {
                try {
                    renameFile();
                    commitEdit(fileName.getText());
                } catch (IOException e) {
                    displayInformationDialog("File rename error", "Could not rename file", e.getLocalizedMessage());
                }
            } else if (event.getCode() == KeyCode.ESCAPE) {
                cancelEdit();
            }
        });

    }

    private void renameFile() throws IOException {
        FilePathTreeItem treeItem = (FilePathTreeItem) getTreeItem();
        Path source = Paths.get(treeItem.getFullPath());
        Files.move(source, source.resolveSibling(fileName.getText()));
    }

    private String getFileName() {
        return getItem() == null ? "" : getItem().toString();
    }

    private void displayInformationDialog(String title, String header, String content) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle(title);
            alert.setHeaderText(header);
            alert.setHeaderText(content);
            alert.showAndWait();
        });
    }

    private Optional<String> createTextInputDialog(String title, String header, String content) {
        TextInputDialog textInputDialog = new TextInputDialog();
        textInputDialog.setTitle(title);
        textInputDialog.setHeaderText(header);
        textInputDialog.setContentText(content);
        return textInputDialog.showAndWait();
    }
}


text:
#ifndef CONTACTSDIALOG_H
#define CONTACTSDIALOG_H

#include <QtGui/QDialog>
#include <QListWidget>
#include <QPointer>

// QtMobility API headers
// Contacts
#include <QContactManager>
#include <QContactPhoneNumber>
#include <QContactSortOrder>
#include <QContact>
#include <QContactName>

// QtMobility namespace
QTM_USE_NAMESPACE

class ContactsDialog: public QDialog
{
Q_OBJECT

public:
    ContactsDialog(QWidget *parent = 0);
    ~ContactsDialog();

public slots:
    void itemClicked(QListWidgetItem *item);
    void selectContact();

signals:
    void contactSelected(QString phoneNumber);

private:
    void createContactManager();
    void searchContact();

private:
    QPointer<QContactManager> m_contactManager;
    QListWidget* m_listWidget;
};

#endif // CONTACTSDIALOG_H


text:
<?php

namespace Bcastellano\JsonSchemaBundle\Validator;

use Bcastellano\JsonSchemaBundle\Exception\JsonSchemaFileNotFoundException;
use Bcastellano\JsonSchemaBundle\Exception\JsonSchemaValidationException;
use Bcastellano\JsonSchemaBundle\Generator\SchemaFileGeneratorInterface;
use Bcastellano\JsonSchemaBundle\Locator\SchemaFileLocatorInterface;
use JsonSchema\Constraints\ConstraintInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class JsonSchemaValidator implements JsonSchemaValidatorInterface
{
    /** @var ConstraintInterface */
    protected $validator;

    /** @var SchemaFileLocatorInterface */
    protected $schemaFileLocator;

    /** @var SchemaFileGeneratorInterface|null */
    protected $schemaFileGenerator;

    /** @var LoggerInterface|null */
    protected $logger;

    /**
     * JsonSchemaValidator constructor.
     *
     * @param ConstraintInterface $validator
     * @param SchemaFileLocatorInterface $schemaFileLocator
     * @param SchemaFileGeneratorInterface|null $schemaFileGenerator
     * @param LoggerInterface|null $logger
     */
    public function __construct(
        ConstraintInterface $validator,
        SchemaFileLocatorInterface $schemaFileLocator,
        SchemaFileGeneratorInterface $schemaFileGenerator = null,
        LoggerInterface $logger = null
    ){
        $this->validator = $validator;
        $this->schemaFileLocator = $schemaFileLocator;
        $this->schemaFileGenerator = $schemaFileGenerator;
        $this->logger = $logger;
    }

    /**
     * @inheritdoc
     */
    public function validateJson($json, $schemaFile)
    {
        if (!file_exists($schemaFile)) {
            if ($this->schemaFileGenerator) {
                $this->schemaFileGenerator->generate($schemaFile, $json);
            } else {
                throw new JsonSchemaFileNotFoundException($schemaFile);
            }
        }

        // check if json validates against schemaFile
        $this->validator->check(json_decode($json), (object)['$ref' => 'file://' . $schemaFile]);

        if (! $valid=$this->validator->isValid()) {
            if ($this->logger) {
                $this->logger->error("Invalid json file: $schemaFile");
            }
        } else {
            if ($this->logger) {
                $this->logger->debug("Valid json file: $schemaFile");
            }
        }

        return $valid;
    }

    /**
     * @inheritdoc
     */
    public function validateRequestBody(Request $request)
    {
        if (0 !== strpos($request->headers->get('Content-Type'), 'application/json')) {
            return;
        }

        $schemaFilePath = $this->schemaFileLocator->getRequestSchemaFile($request);

        if (! $this->validateJson($request->getContent(), $schemaFilePath)) {
            throw new JsonSchemaValidationException($this->validator->getErrors());
        }
    }

    /**
     * @inheritdoc
     */
    public function validateResponseBody(Request $request, Response $response)
    {
        if (0 !== strpos($response->headers->get('Content-Type'), 'application/json')) {
            return;
        }

        $schemaFilePath = $this->schemaFileLocator->getResponseSchemaFile($request, $response);

        if (! $this->validateJson($response->getContent(), $schemaFilePath)) {
            throw new JsonSchemaValidationException($this->validator->getErrors());
        }
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.messages = exports.ruleName = undefined;

exports.default = function (expectation) {
  return function (root, result) {
    var validOptions = (0, _utils.validateOptions)(result, ruleName, {
      actual: expectation,
      possible: ["short", "long"]
    });
    if (!validOptions) {
      return;
    }

    root.walkDecls(function (decl) {
      var declString = decl.toString();

      (0, _utils.styleSearch)({ source: declString, target: "#" }, function (match) {

        var hexMatch = /^#[0-9A-Za-z]+/.exec(declString.substr(match.startIndex));
        if (!hexMatch) {
          return;
        }

        var hexValue = hexMatch[0];

        if (expectation === "long" && hexValue.length !== 4 && hexValue.length !== 5) {
          return;
        }

        if (expectation === "short" && (hexValue.length < 6 || !canShrink(hexValue))) {
          return;
        }

        var variant = expectation === "long" ? longer : shorter;

        (0, _utils.report)({
          message: messages.expected(hexValue, variant(hexValue)),
          node: decl,
          index: match.startIndex,
          result: result,
          ruleName: ruleName
        });
      });
    });
  };
};

var _utils = require("../../utils");

var ruleName = exports.ruleName = "color-hex-length";

var messages = exports.messages = (0, _utils.ruleMessages)(ruleName, {
  expected: function expected(h, v) {
    return "Expected \"" + h + "\" to be \"" + v + "\"";
  }
});

function canShrink(hex) {
  hex = hex.toLowerCase();

  return hex[1] === hex[2] && hex[3] === hex[4] && hex[5] === hex[6] && (hex.length === 7 || hex.length === 9 && hex[7] === hex[8]);
}

function shorter(hex) {
  var hexVariant = "#";
  for (var i = 1; i < hex.length; i = i + 2) {
    hexVariant += hex[i];
  }
  return hexVariant;
}

function longer(hex) {
  var hexVariant = "#";
  for (var i = 1; i < hex.length; i++) {
    hexVariant += hex[i] + hex[i];
  }
  return hexVariant;
}


text:
<?php namespace App\Http\Controllers;

use App\Photo;
use App\PhotoAlbum;

class PhotoController extends Controller {

    public function __construct()
    {
        $this->middleware('auth', [ 'except' => [ 'index', 'show' ] ]);
    }

    public function show($id)
	{
        $photo_album = PhotoAlbum::find($id);
        $photos = Photo::where('photo_album_id', $id)->get();

        return view('photo.view_album',compact('photos','photo_album'));
	}

}