text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>hello world · </title>

  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/poole.css">
  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/hyde.css">
  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/poole-overrides.css">
  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/hyde-overrides.css">
  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/hyde-x.css">
  <link rel="stylesheet" href="https://michaelspets.github.io/blog/css/highlight/zenburn.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://michaelspets.github.io/touch-icon-144-precomposed.png">
  <link href="https://michaelspets.github.io/favicon.png" rel="icon">

  <meta name="description" content="">
  <meta name="keywords" content="">

Home

About

Copyright © 2016 License

       Powered by Hugo and Hyde-X

hello world

    May 12, 2016 · 1 minute read · Comments

    updates

Hello World! This is the first blog post in my brand new blog which was built by an Amit Saha’s article in Linux Voice. I will be using this
blog as a place to post my notes on everyday things I learn. I hope you will like it.

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus


text:
<body>

	<p>Welcome: <?php echo $this->session->userdata('eid'); ?>	<?php echo anchor('login/logout','logout'); ?> </p>

	CREATE RESOURCE ACCOUNT :<?php if($this->session->flashdata('message')){ echo $this->session->flashdata('message'); } ?>

	<?php echo form_open_multipart('user/add_user'); ?>

	Enterprise ID:
	<?php echo form_input('eid', set_value('eid')); ?> <?php echo form_error('eid'); ?>

	Level:
	<?php $team = array ('12' => 'Associate Software Engineer', '11' => 'Software Engineer', '10' => 'Senior Software Engineer', '9' => 'Team Lead', '8' => 'Associate Manager', '7' => 'Project Manager', '6' => 'Senior Project Manager' ); ?>
	<?php echo form_dropdown('career_level_id',$team); ?> <?php echo form_error('career_level_id'); ?>

	Team:
	<?php $team = array ('1' => 'ETL', '2' => '.NET', '3' => 'C++', '4' => 'Java', '5' => 'PHP', '6' => 'PL/SQL', '7' => 'System Test' ); ?>
	<?php echo form_dropdown('team_id',$team); ?> <?php echo form_error('team_id'); ?>

	User Type:
	<?php $type = array ('User' => 'User', 'Lead' => 'Lead'); ?>
	<?php echo form_dropdown('user_type',$type); ?> <?php echo form_error('user_type'); ?>

	Tagged as Administrator:
	<?php $is_admin = array ('0' => 'No', '1' => 'Yes'); ?>
	<?php echo form_dropdown('is_admin',$is_admin); ?> <?php echo form_error('is_admin'); ?>

	Tagged as Quality Representative:
	<?php $is_qa_rep = array ('0' => 'No', '1' => 'Yes'); ?>
	<?php echo form_dropdown('is_qa_rep',$is_qa_rep); ?> <?php echo form_error('is_qa_rep'); ?>

	<?php echo form_submit('submit','Create');?>

	<?php echo form_close(); ?>

</body>

redpajama_set_name: RedPajamaGithub


text:
package jsjf.exceptions;

/**
 * Represents the situation in which a collection is empty.
 *
 * @author Java Foundations
 * @version 4.0
 */
public class EmptyCollectionException extends RuntimeException
{
    /**
     * Sets up this exception with an appropriate message.
     * @param collection the name of the collection
     */
    public EmptyCollectionException(String collection)
    {
        super("The " + collection + " is empty.");
    }
}


text:
module Controlroom
  class Engine < ::Rails::Engine
    isolate_namespace Controlroom
  end
end


text:
package com.github.maven_nar.cpptasks.devstudio;
import java.io.File;
import java.util.Vector;

import com.github.maven_nar.cpptasks.CUtil;
import com.github.maven_nar.cpptasks.compiler.CommandLineCompiler;
import com.github.maven_nar.cpptasks.compiler.LinkType;
import com.github.maven_nar.cpptasks.compiler.Linker;
import com.github.maven_nar.cpptasks.compiler.Processor;
import com.github.maven_nar.cpptasks.parser.Parser;
import com.github.maven_nar.cpptasks.OptimizationEnum;

import org.apache.tools.ant.types.Environment;
/**
 * Adapter for the Microsoft (r) Windows 32 Message Compiler
 *
 * @author Greg Domjan
 *
 * MC [-?aAbcdnouUv] [-co] [-cs namespace] [-css namespace] [-e extension]
 *    [-h path] [-km] [-m length] [-mof] [-p prefix] [-P prefix] [-r path]
 *    [-s path] [-t path] [-w path] [-W path] [-x path] [-z name]
 *    filename [filename]
 */
public final class DevStudioMessageCompiler extends CommandLineCompiler {
    private static final DevStudioMessageCompiler instance = new DevStudioMessageCompiler(
            false, null);

    public static DevStudioMessageCompiler getInstance() {
        return instance;
    }

    private DevStudioMessageCompiler(boolean newEnvironment, Environment env) {
        super("mc", null, new String[]{".mc",".man"}, new String[]{},
            ".rc", false, null, newEnvironment, env);
    }
    protected void addImpliedArgs(final Vector args,
            final boolean debug,
            final boolean multithreaded,
	    final boolean exceptions,
	    final LinkType linkType,
	    final Boolean rtti,
	    final OptimizationEnum optimization) {
        // no identified configuration compiler arguments implied from these options.
    }

    protected void addWarningSwitch(Vector args, int level) {
    }

    public Processor changeEnvironment(boolean newEnvironment, Environment env) {
        if (newEnvironment || env != null) {
            return new DevStudioMessageCompiler(newEnvironment, env);
        }
        return this;
    }

    protected boolean canParse(File sourceFile){ return false; }

    protected Parser createParser(File source) {
    	// neither file type has references to other elements that need to be found through parsing.
        return null;
    }

    protected int getArgumentCountPerInputFile() {
        return 3;
    }

    protected void getDefineSwitch(StringBuffer buffer, String define,
            String value) {
        // no define switch
    }

    protected File[] getEnvironmentIncludePath() {
        return CUtil.getPathFromEnvironment("INCLUDE", ";");
    }

    protected void addIncludes(String baseDirPath, File[] includeDirs,
            Vector args, Vector relativeArgs, StringBuffer includePathId,
	    boolean isSystem) {
    	// no include switch
    	// for some reason we are still getting args in the output??
    }

    protected String getIncludeDirSwitch(String includeDir) {
        return null; // no include switch
    }

    protected String getInputFileArgument(File outputDir, String filename,
            int index) {
        switch (index) {
	        case 0 :
	            return "-r";
	        case 1 :
	            return outputDir.getAbsolutePath();
	    }
        return filename;
    }
    public Linker getLinker(LinkType type) {
        return DevStudioLinker.getInstance().getLinker(type);
    }

    public int getMaximumCommandLength() {
        return 32000;
    }

    protected int getMaximumInputFilesPerCommand() {
        return 1;
    }

    protected int getTotalArgumentLengthForInputFile(File outputDir,
            String inputFile) {
        String arg1 = getInputFileArgument(outputDir, inputFile, 0);
        String arg2 = getInputFileArgument(outputDir, inputFile, 1);
        return arg1.length() + arg2.length() + 2;
    }

    protected void getUndefineSwitch(StringBuffer buffer, String define) {
        DevStudioProcessor.getUndefineSwitch(buffer, define);
    }

    public String getIdentifier() {
    	return "Microsoft (R) Windows (R) Message Compiler";
    }
}


text:
namespace chromeos {

// Constants for ONC properties.
namespace onc {

extern const char kEthernet[];
extern const char kGUID[];
extern const char kName[];
extern const char kNetworkConfiguration[];
extern const char kProxySettings[];
extern const char kRecommended[];
extern const char kRemove[];
extern const char kType[];
extern const char kVPN[];
extern const char kWiFi[];

namespace ethernet {
extern const char kAuthentication[];
extern const char kEAP[];
}  // namespace ethernet

namespace wifi {
extern const char kAutoConnect[];
extern const char kEAP[];
extern const char kHiddenSSID[];
extern const char kPassphrase[];
extern const char kProxyURL[];
extern const char kSecurity[];
extern const char kSSID[];
}  // namespace wifi

namespace certificate {
extern const char kCommonName[];
extern const char kEmailAddress[];
extern const char kEnrollmentURI[];
extern const char kIssuer[];
extern const char kIssuerCARef[];
extern const char kLocality[];
extern const char kNone[];
extern const char kOrganization[];
extern const char kOrganizationalUnit[];
extern const char kPattern[];
extern const char kRef[];
extern const char kSubject[];
}  // namespace certificate

namespace eap {
extern const char kAnonymousIdentity[];
extern const char kClientCertPattern[];
extern const char kClientCertRef[];
extern const char kClientCertType[];
extern const char kIdentity[];
extern const char kInner[];
extern const char kOuter[];
extern const char kPassword[];
extern const char kSaveCredentials[];
extern const char kServerCARef[];
extern const char kUseSystemCAs[];
}  // namespace eap

namespace vpn {
extern const char kAuthNoCache[];
extern const char kAuthRetry[];
extern const char kAuth[];
extern const char kAuthenticationType[];
extern const char kCipher[];
extern const char kClientCertPattern[];
extern const char kClientCertRef[];
extern const char kClientCertType[];
extern const char kCompLZO[];
extern const char kCompNoAdapt[];
extern const char kGroup[];
extern const char kHost[];
extern const char kIKEVersion[];
extern const char kIPsec[];
extern const char kKeyDirection[];
extern const char kL2TP[];
extern const char kNsCertType[];
extern const char kOpenVPN[];
extern const char kPSK[];
extern const char kPassword[];
extern const char kPort[];
extern const char kProto[];
extern const char kPushPeerInfo[];
extern const char kRemoteCertEKU[];
extern const char kRemoteCertKU[];
extern const char kRemoteCertTLS[];
extern const char kRenegSec[];
extern const char kSaveCredentials[];
extern const char kServerCARef[];
extern const char kServerCertRef[];
extern const char kServerPollTimeout[];
extern const char kShaper[];
extern const char kStaticChallenge[];
extern const char kTLSAuthContents[];
extern const char kTLSRemote[];
extern const char kType[];
extern const char kUsername[];
}  // namespace vpn

namespace substitutes {
extern const char kEmailField[];
extern const char kLoginIDField[];
}  // namespace substitutes

namespace proxy {
extern const char kDirect[];
extern const char kExcludeDomains[];
extern const char kFtp[];
extern const char kHost[];
extern const char kHttp[];
extern const char kHttps[];
extern const char kManual[];
extern const char kPAC[];
extern const char kPort[];
extern const char kSocks[];
extern const char kType[];
extern const char kWPAD[];
}  // namespace proxy

}  // namespace onc

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_CROS_ONC_CONSTANTS_H_


text:
import LoginPage from './LoginPage'

export default LoginPage


text:
module RuboCop
  module Cop
    module Style
      # Checks for case statements with an empty condition.
      #
      # @example
      #
      #   # bad:
      #   case
      #   when x == 0
      #     puts 'x is 0'
      #   when y == 0
      #     puts 'y is 0'
      #   else
      #     puts 'neither is 0'
      #   end
      #
      #   # good:
      #   if x == 0
      #     puts 'x is 0'
      #   elsif y == 0
      #     puts 'y is 0'
      #   else
      #     puts 'neither is 0'
      #   end
      #
      #   # good: (the case condition node is not empty)
      #   case n
      #   when 0
      #     puts 'zero'
      #   when 1
      #     puts 'one'
      #   else
      #     puts 'more'
      #   end
      class EmptyCaseCondition < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Do not use empty `case` condition, instead use an `if` expression.'

        def on_case(case_node)
          return if case_node.condition

          branch_bodies = [*case_node.when_branches.map(&:body), case_node.else_branch].compact

          return if branch_bodies.any? do |body|
            body.return_type? || body.each_descendant.any?(&:return_type?)
          end

          add_offense(case_node.loc.keyword) { |corrector| autocorrect(corrector, case_node) }
        end

        private

        def autocorrect(corrector, case_node)
          when_branches = case_node.when_branches

          correct_case_when(corrector, case_node, when_branches)
          correct_when_conditions(corrector, when_branches)
        end

        def correct_case_when(corrector, case_node, when_nodes)
          case_range = case_node.loc.keyword.join(when_nodes.first.loc.keyword)

          corrector.replace(case_range, 'if')

          keep_first_when_comment(case_range, corrector)

          when_nodes[1..].each do |when_node|
            corrector.replace(when_node.loc.keyword, 'elsif')
          end
        end

        def correct_when_conditions(corrector, when_nodes)
          when_nodes.each do |when_node|
            conditions = when_node.conditions

            replace_then_with_line_break(corrector, conditions, when_node)

            next unless conditions.size > 1

            range = range_between(conditions.first.source_range.begin_pos,
                                  conditions.last.source_range.end_pos)

            corrector.replace(range, conditions.map(&:source).join(' || '))
          end
        end

        def keep_first_when_comment(case_range, corrector)
          indent = ' ' * case_range.column
          comments = processed_source.each_comment_in_lines(
            case_range.first_line...case_range.last_line
          ).map { |comment| "#{indent}#{comment.text}\n" }.join

          line_beginning = case_range.adjust(begin_pos: -case_range.column)
          corrector.insert_before(line_beginning, comments)
        end

        def replace_then_with_line_break(corrector, conditions, when_node)
          return unless when_node.parent.parent && when_node.then?

          range = range_between(conditions.last.source_range.end_pos, when_node.loc.begin.end_pos)

          corrector.replace(range, "\n")
        end
      end
    end
  end
end


text:
    (function() {
      if (hasShadowDOM) {
        var elementsCreated = 0;
        // basic proto
        var proto = Object.create(HTMLElement.prototype);
        proto.createdCallback = function() {
          elementsCreated++;
        };
        // extend to create shadowRoot containing a custom element
        var hostProto = Object.create(proto);
        hostProto.createdCallback = function() {
          proto.createdCallback.call(this);
          chai.assert.equal(elementsCreated, 1, 'upgraded element');
          var root = this.createShadowRoot();
          // create element via innerHTML
          root.innerHTML = '<x-foo></x-foo>';
          CustomElements.takeRecords(root);
          chai.assert.equal(elementsCreated, 2, 'upgraded element inside shadowRoot');
          // now create async to test if the shadowRoot MutationObserver sees
          setTimeout(function() {
            root.innerHTML = '<x-foo></x-foo>';
            CustomElements.takeRecords(root);
            chai.assert.equal(elementsCreated, 3, 'upgraded element created async inside shadowRoot');
            done();
          }, 50);

        };
        document.registerElement('x-foo', {prototype: proto});
        document.registerElement('x-host', {prototype: hostProto});
      } else {
        done();
      }
    })();


text:
LEVEL := ../..
TOOLNAME := macho-dump
LINK_COMPONENTS := support object

# This tool has no plugins, optimize startup time.
TOOL_NO_EXPORTS := 1

include $(LEVEL)/Makefile.common


text:
using System;
using System.Runtime.InteropServices;
using Gdk;
using Gtk;
using FSpot.Utils;
using Hyena;

namespace FSpot.Gui {

	public class CompositeUtils {
		[DllImport("libgdk-2.0-0.dll")]
	        static extern bool gdk_screen_is_composited (IntPtr screen);

		[DllImport("libgdk-2.0-0.dll")]
		static extern bool gdk_x11_screen_supports_net_wm_hint (IntPtr screen,
									IntPtr property);

		[DllImport("libgdk-2.0-0.dll")]
		static extern IntPtr gdk_screen_get_rgba_colormap (IntPtr screen);

		[DllImport("libgdk-2.0-0.dll")]
		static extern IntPtr gdk_screen_get_rgba_visual (IntPtr screen);

		[DllImport ("libgtk-win32-2.0-0.dll")]
		static extern void gtk_widget_input_shape_combine_mask (IntPtr raw, IntPtr shape_mask, int offset_x, int offset_y);

		[DllImport("libgdk-2.0-0.dll")]
		static extern void gdk_property_change(IntPtr window, IntPtr property, IntPtr type, int format, int mode, uint [] data, int nelements);

		[DllImport("libgdk-2.0-0.dll")]
		static extern void gdk_property_change(IntPtr window, IntPtr property, IntPtr type, int format, int mode, byte [] data, int nelements);

		public static Colormap GetRgbaColormap (Screen screen)
		{
			try {
				IntPtr raw_ret = gdk_screen_get_rgba_colormap (screen.Handle);
				Gdk.Colormap ret = GLib.Object.GetObject(raw_ret) as Gdk.Colormap;
				return ret;
			} catch {
				Gdk.Visual visual = Gdk.Visual.GetBestWithDepth (32);
				if (visual != null) {
					Gdk.Colormap cmap = new Gdk.Colormap (visual, false);
					Log.Debug ("fallback");
					return cmap;
				}
			}
			return null;
		}

		public static void  ChangeProperty (Gdk.Window win, Atom property, Atom type, PropMode mode, uint [] data)
		{
			gdk_property_change (win.Handle, property.Handle, type.Handle, 32, (int)mode,  data, data.Length * 4);
		}

		public static void  ChangeProperty (Gdk.Window win, Atom property, Atom type, PropMode mode, byte [] data)
		{
			gdk_property_change (win.Handle, property.Handle, type.Handle, 8, (int)mode,  data, data.Length);
		}

		public static bool SupportsHint (Screen screen, string name)
		{
			try {
				Atom atom = Atom.Intern (name, false);
				return gdk_x11_screen_supports_net_wm_hint (screen.Handle, atom.Handle);
			} catch {

				return false;
			}
		}

		public static bool SetRgbaColormap (Widget w)
		{
			Gdk.Colormap cmap = GetRgbaColormap (w.Screen);

			if (cmap != null) {
				w.Colormap = cmap;
				return true;
			}

			return false;
		}

		public static Visual GetRgbaVisual (Screen screen)
		{
			try {
				IntPtr raw_ret = gdk_screen_get_rgba_visual (screen.Handle);
				Gdk.Visual ret = GLib.Object.GetObject(raw_ret) as Gdk.Visual;
				return ret;
			} catch {
				Gdk.Visual visual = Gdk.Visual.GetBestWithDepth (32);
				if (visual != null) {
					return visual;
				}
			}
			return null;
		}

		public static bool IsComposited (Screen screen) {
			bool composited;
			try {
				composited = gdk_screen_is_composited (screen.Handle);
			} catch (EntryPointNotFoundException) {
				Log.Debug ("query composite manager locally");
				Atom atom = Atom.Intern (String.Format ("_NET_WM_CM_S{0}", screen.Number), false);
				composited = Gdk.Selection.OwnerGetForDisplay (screen.Display, atom) != null;
			}

			// FIXME check for WINDOW_OPACITY so that we support compositing on older composite manager
			// versions before they started supporting the real check given above
			if (!composited)
				composited = CompositeUtils.SupportsHint (screen, "_NET_WM_WINDOW_OPACITY");

			return composited;
		}

		public static void InputShapeCombineMask (Widget w, Pixmap shape_mask, int offset_x, int offset_y)
		{
			gtk_widget_input_shape_combine_mask (w.Handle, shape_mask == null ? IntPtr.Zero : shape_mask.Handle, offset_x, offset_y);
		}

		[DllImport("libXcomposite.dll")]
		static extern void XCompositeRedirectWindow (IntPtr display, uint window, CompositeRedirect update);

		public enum CompositeRedirect {
			Automatic = 0,
			Manual = 1
		};

		public static void RedirectDrawable (Drawable d)
		{
			uint xid = GdkUtils.GetXid (d);
			Log.DebugFormat ("xid = {0} d.handle = {1}, d.Display.Handle = {2}", xid, d.Handle, d.Display.Handle);
			XCompositeRedirectWindow (GdkUtils.GetXDisplay (d.Display), GdkUtils.GetXid (d), CompositeRedirect.Manual);
		}

		public static void SetWinOpacity (Gtk.Window win, double opacity)
		{
			CompositeUtils.ChangeProperty (win.GdkWindow,
						       Atom.Intern ("_NET_WM_WINDOW_OPACITY", false),
						       Atom.Intern ("CARDINAL", false),
						       PropMode.Replace,
						       new uint [] { (uint) (0xffffffff * opacity) });
		}

		public static Cms.Profile GetScreenProfile (Screen screen)
		{
			Atom atype;
			int  aformat;
			int  alength;
			byte [] data;

			if (Gdk.Property.Get (screen.RootWindow,
					      Atom.Intern ("_ICC_PROFILE", false),
					      Atom.Intern ("CARDINAL", false),
					      0,
					      Int32.MaxValue,
					      0, // FIXME in gtk# should be a bool
					      out atype,
					      out aformat,
					      out alength,
					      out data)) {
				return new Cms.Profile (data);
			}

			return null;
		}

		public static void SetScreenProfile (Screen screen, Cms.Profile profile)
		{
			byte [] data = profile.Save ();
			ChangeProperty (screen.RootWindow,
					Atom.Intern ("_ICC_PROFILE", false),
					Atom.Intern ("CARDINAL", false),
					PropMode.Replace,
					data);
		}
	}
}


text:
.. _plugins-overriding-publishable-urls:

Overriding Publishable URLs
###########################

Adding custom actions
*********************

Consider a situation, when we would like to have discussion about the video on
a separate page while **keeping the nice URL** prefix Ella creates for it's
publishable objects. There is a simple solution for that. Ella's custom URL
resolver allows us to **add actions** for the Publishable objects easily.

We would like our URL to have following form::

    /about/2007/08/11/videos/ella-first-in-production/discussion/

To do this, we will append a custom view function for the ``Video`` model::

    # in yourapp/video/urls.py
    from django.conf.urls.defaults import url, patterns

    from ella.core.custom_urls import resolver

    from yourapp.models import Video
    from yourapp.video.views import show_discussion

    urlpatterns = patterns('',
        url(r'^discussion/$', show_discussion, name='video-show-discussions'),
    )

    resolver.register(urlpatterns, model=Video)

When registering custom URLs, we use ``ella.core.custom_urls.resolver`` instead
of regular Django url machinery. This does a little Python magic so that your
URLs will be appended to base Publishable URL. Note the use of ``model``
argument in ::

    resolver.register(urlpatterns, model=Video)

This means, that the custom action will be available only for a ``Video`` model.
If we wanted to add our *discussion action* to all Publishable models, we would
simply omit the ``model`` argument altogether.

As you have probably noticed, we are using ``show_discussion`` view function
without declaring it, let's fix that up::

    # in yourapp/video/views.py

    def show_discussion(request, context):
        obj = context['object']
        return render('yourapp/discussion.html', {'object': obj})

Views that are used with Ella's resolver always accept ``request`` (which is a
normal Django request object) and ``context`` which is a dictionary that
contains following data:

.. _plugins-custom-view-aguments:

.. table:: Custom view arguments

    ==================================  ================================================
    Key                                 Value
    ==================================  ================================================
    ``object``                          The publishable object itself.
    ``category``                        ``Category`` object related to the URL.
    ``content_type_name``               Verbose name of Content type of the Publishable
                                        (e.g. Article, Video and so on).
    ``content_type``                    ``ContentType`` instance for Publishable.
    ==================================  ================================================

Overriding objects' detail
**************************

Besides custom actions, it is also possible to completely override the view
which handles rendering of object detail page. Such a requirement might occur
in these situations:

* You need to add custom object-related data to the **context** in the detail
  template.
* You wish to change the way the view itself **works**. This can be used for
  advanced behavior changes which are needed only rarely.

To define a custom view, we will use the Ella's URL resolver again::

    # in your urls.py
    from django.conf.urls.defaults import patterns, url

    from ella.core.custom_urls import resolver

    from yourapp.models import Video
    from yourapp.views import video_detail

    resolver.register_custom_detail(Video, article_detail)

This will result in calling our ``article_detail`` view instead of the default
one. Custom detail views are called with same arguments as custom action views.
For reference, see the table with custom view arguments above. For further information
on Ella's ``ObjectDetailView``, see :ref:`reference-views`.


text:
package net.ssehub.easy.instantiation.core.model.vilTypes.configuration;

import java.util.HashSet;
import java.util.Set;

import net.ssehub.easy.varModel.model.Project;

/**
 * A project-based filter, i.e., all {@link IvmlElement elements} contained in a project
 * shall be included by this filter.
 *
 * @author Holger Eichelberger
 */
class ProjectFilter implements IConfigurationFilter {

    private Project project;
    private boolean considerImports;
    private IConfigurationFilter further;

    /**
     * Creates a filter.
     *
     * @param project the project to filter for
     * @param considerImports the imports of project
     */
    public ProjectFilter(Project project, boolean considerImports) {
        this(project, considerImports, null);
    }

    /**
     * Creates a filter.
     *
     * @param project the project to filter for (may be null, then the filter rejects all elements)
     * @param considerImports the imports of project
     * @param further an (optional) filter to be considered (may be null)
     */
    public ProjectFilter(Project project, boolean considerImports, IConfigurationFilter further) {
        this.further = further;
        this.project = project;
        this.considerImports = considerImports;
    }

    /**
     * Checks whether element shall be included due to its membership in project.
     *
     * @param element the element to consider
     * @param project the project to ask for element
     * @param done already considered projects to control cyclic imports
     * @return true if element shall be included, false else
     */
    private boolean include(IvmlElement element, Project project, Set<Project> done) {
        boolean result;
        if (null == project) {
            result = false;
        } else {
            result = project.containsByName(element.getQualifiedName());
            if (!result && considerImports) {
                if (!done.contains(project)) {
                    done.add(project);
                    for (int i = 0; !result && i < project.getImportsCount(); i++) {
                        result = include(element, project.getImport(i).getResolved(), done);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public boolean include(IvmlElement element) {
        return checkFurther(element, include(element, project, new HashSet<Project>()));
    }

    /**
     * Checks whether {@link #further} applies.
     *
     * @param element the element to be tested
     * @param result the result determined for including element so far
     * @return true if element shall be included, false else
     */
    private boolean checkFurther(IvmlElement element, boolean result) {
        if (result && null != further) {
            result = further.include(element);
        }
        return result;
    }

}


text:
package com.salesforce.hbase.index.wal;

import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
import org.apache.hadoop.hbase.util.Bytes;

import com.salesforce.hbase.index.util.ImmutableBytesPtr;

public class IndexedKeyValue extends KeyValue {
    private static int calcHashCode(ImmutableBytesPtr indexTableName, Mutation mutation) {
        final int prime = 31;
        int result = 1;
        result = prime * result + indexTableName.hashCode();
        result = prime * result + Arrays.hashCode(mutation.getRow());
        return result;
    }

    private ImmutableBytesPtr indexTableName;
    private Mutation mutation;
    // optimization check to ensure that batches don't get replayed to the index more than once
    private boolean batchFinished = false;
    private int hashCode;

    public IndexedKeyValue() {}

    public IndexedKeyValue(byte[] bs, Mutation mutation) {
        this.indexTableName = new ImmutableBytesPtr(bs);
        this.mutation = mutation;
        this.hashCode = calcHashCode(indexTableName, mutation);
    }

    public byte[] getIndexTable() {
        return this.indexTableName.get();
    }

    public Mutation getMutation() {
        return mutation;
    }

    /**
     * This is a KeyValue that shouldn't actually be replayed, so we always mark it as an {@link HLog#METAFAMILY} so it
     * isn't replayed via the normal replay mechanism
     */
    @Override
    public boolean matchingFamily(final byte[] family) {
        return Bytes.equals(family, HLog.METAFAMILY);
    }

    @Override
    public String toString() {
        return "IndexWrite:\n\ttable: " + indexTableName + "\n\tmutation:" + mutation;
    }

    /**
     * This is a very heavy-weight operation and should only be done when absolutely necessary - it does a full
     * serialization of the underyling mutation to compare the underlying data.
     */
    @Override
    public boolean equals(Object obj) {
        if(obj == null) return false;
        if (this == obj) return true;
        if (getClass() != obj.getClass()) return false;
        IndexedKeyValue other = (IndexedKeyValue)obj;
        if (hashCode() != other.hashCode()) return false;
        if (!other.indexTableName.equals(this.indexTableName)) return false;
        byte[] current = this.getMutationBytes();
        byte[] otherMutation = other.getMutationBytes();
        return Bytes.equals(current, otherMutation);
    }

    private byte[] getMutationBytes() {
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            this.mutation.write(new DataOutputStream(bos));
            bos.flush();
            return bos.toByteArray();
        } catch (IOException e) {
            throw new IllegalArgumentException("Failed to get bytes for mutation!", e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new IllegalArgumentException("Failed to get bytes for mutation!", e);
                }
            }
        }
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        KeyValueCodec.write(out, this);
    }

    /**
     * Internal write the underlying data for the entry - this does not do any special prefixing. Writing should be done
     * via {@link KeyValueCodec#write(DataOutput, KeyValue)} to ensure consistent reading/writing of
     * {@link IndexedKeyValue}s.
     *
     * @param out
     *            to write data to. Does not close or flush the passed object.
     * @throws IOException
     *             if there is a problem writing the underlying data
     */
    void writeData(DataOutput out) throws IOException {
        Bytes.writeByteArray(out, this.indexTableName.get());
        out.writeUTF(this.mutation.getClass().getName());
        this.mutation.write(out);
    }

    /**
     * This method shouldn't be used - you should use {@link KeyValueCodec#readKeyValue(DataInput)} instead. Its the
     * complement to {@link #writeData(DataOutput)}.
     */
    @SuppressWarnings("javadoc")
    @Override
    public void readFields(DataInput in) throws IOException {
        this.indexTableName = new ImmutableBytesPtr(Bytes.readByteArray(in));
        Class<? extends Mutation> clazz;
        try {
            clazz = Class.forName(in.readUTF()).asSubclass(Mutation.class);
            this.mutation = clazz.newInstance();
            this.mutation.readFields(in);
            this.hashCode = calcHashCode(indexTableName, mutation);
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        } catch (InstantiationException e) {
            throw new IOException(e);
        } catch (IllegalAccessException e) {
            throw new IOException(e);
        }
    }

    public boolean getBatchFinished() {
        return this.batchFinished;
    }

    public void markBatchFinished() {
        this.batchFinished = true;
    }
}


text:
package com.google.cloud.graphite.platforms.plugin.client;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.services.container.Container;
import com.google.api.services.container.model.Cluster;
import java.io.IOException;
import java.util.List;

/*
 * Internal use only. Wraps chained methods with direct calls for readability and mocking. The lack
 * of final parameters or parameter checking is intended, this is purely for wrapping.
 */
class ContainerWrapper {
  private static final String GET_RESOURCE_URL = "https://%s/v2/%s/%s/manifests/%s";
  private static final String MANIFEST_ACCEPT_TYPE =
      "application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.v2+json";
  private static final String DIGEST_HEADER = "docker-content-digest";
  private final Container container;

  ContainerWrapper(Container container) {
    this.container = container;
  }

  Cluster getCluster(String projectId, String location, String clusterName) throws IOException {
    return container
        .projects()
        .locations()
        .clusters()
        .get(toApiName(projectId, location, clusterName))
        .execute();
  }

  List<Cluster> listClusters(String projectId, String location) throws IOException {
    return container
        .projects()
        .locations()
        .clusters()
        .list(toApiParent(projectId, location))
        .execute()
        .getClusters();
  }

  String getDigest(String domain, String projectId, String name, String tag) throws IOException {
    HttpRequest request =
        container
            .getRequestFactory()
            .buildGetRequest(
                new GenericUrl(String.format(GET_RESOURCE_URL, domain, projectId, name, tag)));
    HttpHeaders headers = request.getHeaders();
    headers.setAccept(MANIFEST_ACCEPT_TYPE);
    return request
        .setHeaders(headers)
        .execute()
        .getHeaders()
        .getFirstHeaderStringValue(DIGEST_HEADER);
  }

  private static String toApiName(
      final String projectId, final String location, final String clusterName) {
    return String.format("projects/%s/locations/%s/clusters/%s", projectId, location, clusterName);
  }

  private static String toApiParent(final String projectId, final String location) {
    return String.format("projects/%s/locations/%s", projectId, location);
  }
}


text:
'use strict';

var yamlLoader      = require(__dirname + '/file.js'),
    fs              = require('fs');

function getYamlName(filename) {
    filename = String(filename);
    return (filename.length > 4 && filename.substr(-4).toLowerCase() === '.yml') ? filename.substr(0, filename.length - 4) : false;
}

module.exports = {
    load: function (path, encoding) {
        if (!fs.existsSync(path)) {
            return false;
        }
        path = fs.realpathSync(path);
        if (!path) {
            return false;
        }
        var files = fs.readdirSync(path),
            i,
            result = {},
            name;

        for (i = 0; i < files.length; i++) {
            if ((name = getYamlName(files[i])) !== false) {
                result[name] = yamlLoader.load(path + '/' + files[i]);
            }
        }

        return result;
    }
};


text:
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// add a new dom element
frappe.provide('frappe.dom');

frappe.dom = {
	id_count: 0,
	freeze_count: 0,
	by_id: function(id) {
		return document.getElementById(id);
	},
	set_unique_id: function(ele) {
		var $ele = $(ele);
		if($ele.attr('id')) {
			return $ele.attr('id');
		}
		var id = 'unique-' + frappe.dom.id_count;
		$ele.attr('id', id);
		frappe.dom.id_count++;
		return id;
	},
	eval: function(txt) {
		if(!txt) return;
		var el = document.createElement('script');
		el.appendChild(document.createTextNode(txt));
		// execute the script globally
		document.getElementsByTagName('head')[0].appendChild(el);
	},
	remove_script_and_style: function(txt) {
		var div = document.createElement('div');
		div.innerHTML = txt;
		var found = false;
		["script", "style", "noscript", "title", "meta", "base", "head"].forEach(function(e, i) {
			var elements = div.getElementsByTagName(e);
			var i = elements.length;
			while (i--) {
				found = true;
				elements[i].parentNode.removeChild(elements[i]);
			}
		});

		// remove links with rel="stylesheet"
		var elements = div.getElementsByTagName('link');
		var i = elements.length;
		while (i--) {
			if (elements[i].getAttribute("rel")=="stylesheet"){
				found = true;
				elements[i].parentNode.removeChild(elements[i]);
			}
		}
		if(found) {
			return div.innerHTML;
		} else {
			// don't disturb
			return txt;
		}
	},
	is_element_in_viewport: function (el) {

		//special bonus for those using jQuery
		if (typeof jQuery === "function" && el instanceof jQuery) {
			el = el[0];
		}

		var rect = el.getBoundingClientRect();

		return (
			rect.top >= 0
			&& rect.left >= 0
			// && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
			// && rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
		);
	},

	set_style: function(txt, id) {
		if(!txt) return;

		var se = document.createElement('style');
		se.type = "text/css";

		if (id) {
			var element = document.getElementById(id);
			if (element) {
				element.parentNode.removeChild(element);
			}
			se.id = id;
		}

		if (se.styleSheet) {
			se.styleSheet.cssText = txt;
		} else {
			se.appendChild(document.createTextNode(txt));
		}
		document.getElementsByTagName('head')[0].appendChild(se);
		return se;
	},
	add: function(parent, newtag, className, cs, innerHTML, onclick) {
		if(parent && parent.substr)parent = frappe.dom.by_id(parent);
		var c = document.createElement(newtag);
		if(parent)
			parent.appendChild(c);

		// if image, 3rd parameter is source
		if(className) {
			if(newtag.toLowerCase()=='img')
				c.src = className
			else
				c.className = className;
		}
		if(cs) frappe.dom.css(c,cs);
		if(innerHTML) c.innerHTML = innerHTML;
		if(onclick) c.onclick = onclick;
		return c;
	},
	css: function(ele, s) {
		if(ele && s) {
			$.extend(ele.style, s);
		}
		return ele;
	},
	freeze: function(msg, css_class) {
		// blur
		if(!$('#freeze').length) {
			var freeze = $('

')
				.on("click", function() {
					if (cur_frm && cur_frm.cur_grid) {
						cur_frm.cur_grid.toggle_view();
						return false;
					}
				})
				.appendTo("#body_div");

			freeze.html(repl('

%(msg)s

',
				{msg: msg || ""}));

			setTimeout(function() { freeze.addClass("in") }, 1);

		} else {
			$("#freeze").addClass("in");
		}

		if (css_class) {
			$("#freeze").addClass(css_class);
		}

		frappe.dom.freeze_count++;
	},
	unfreeze: function() {
		if(!frappe.dom.freeze_count) return; // anything open?
		frappe.dom.freeze_count--;
		if(!frappe.dom.freeze_count) {
			var freeze = $('#freeze').removeClass("in").remove();
		}
	},
	save_selection: function() {
		// via http://stackoverflow.com/questions/5605401/insert-link-in-contenteditable-element
		if (window.getSelection) {
			var sel = window.getSelection();
			if (sel.getRangeAt && sel.rangeCount) {
				var ranges = [];
				for (var i = 0, len = sel.rangeCount; i < len; ++i) {
					ranges.push(sel.getRangeAt(i));
				}
				return ranges;
			}
		} else if (document.selection && document.selection.createRange) {
			return document.selection.createRange();
		}
		return null;
	},
	restore_selection: function(savedSel) {
		if (savedSel) {
			if (window.getSelection) {
				var sel = window.getSelection();
				sel.removeAllRanges();
				for (var i = 0, len = savedSel.length; i < len; ++i) {
					sel.addRange(savedSel[i]);
				}
			} else if (document.selection && savedSel.select) {
				savedSel.select();
			}
		}
	},
	is_touchscreen: function() {
		return ('ontouchstart' in window)
	}
}

frappe.ellipsis = function(text, max) {
	if(!max) max = 20;
	text = cstr(text);
	if(text.length > max) {
		text = text.substr(0, max) + '...';
	}
	return text;
};

frappe.run_serially = function(tasks) {
	var result = Promise.resolve();
	tasks.forEach(task => {
		if(task) {
			result = result.then ? result.then(task) : Promise.resolve();
		}
	});
	return result;
};

frappe.timeout = seconds => {
	return new Promise((resolve) => {
		setTimeout(() => resolve(), seconds * 1000);
	});
};

frappe.scrub = function(text) {
	return text.replace(/ /g, "_").toLowerCase();
};

frappe.get_modal = function(title, content) {
	return $(frappe.render_template("modal", {title:title, content:content})).appendTo(document.body);
};

// add <option> list to <select>
(function($) {
	$.fn.add_options = function(options_list) {
		// create options
		for(var i=0, j=options_list.length; i<j; i++) {
			var v = options_list[i];
			if (is_null(v)) {
				var value = null;
				var label = null;
			} else {
				var is_value_null = is_null(v.value);
				var is_label_null = is_null(v.label);

				if (is_value_null && is_label_null) {
					var value = v;
					var label = __(v);
				} else {
					var value = is_value_null ? "" : v.value;
					var label = is_label_null ? __(value) : __(v.label);
				}
			}
			$('<option>').html(cstr(label)).attr('value', value).appendTo(this);
		}
		// select the first option
		this.selectedIndex = 0;
		return $(this);
	}
	$.fn.set_working = function() {
		this.prop('disabled', true);
	}
	$.fn.done_working = function() {
		this.prop('disabled', false);
	}
})(jQuery);

(function($) {
	function pasteIntoInput(el, text) {
		el.focus();
		if (typeof el.selectionStart == "number") {
			var val = el.value;
			var selStart = el.selectionStart;
			el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
			el.selectionEnd = el.selectionStart = selStart + text.length;
		} else if (typeof document.selection != "undefined") {
			var textRange = document.selection.createRange();
			textRange.text = text;
			textRange.collapse(false);
			textRange.select();
		}
	}

	function allowTabChar(el) {
		$(el).keydown(function(e) {
			if (e.which == 9) {
				pasteIntoInput(this, "\t");
				return false;
			}
		});

		// For Opera, which only allows suppression of keypress events, not keydown
		$(el).keypress(function(e) {
			if (e.which == 9) {
				return false;
			}
		});
	}

	$.fn.allowTabs = function() {
		if (this.jquery) {
			this.each(function() {
				if (this.nodeType == 1) {
					var nodeName = this.nodeName.toLowerCase();
					if (nodeName == "textarea" || (nodeName == "input" && this.type == "text")) {
						allowTabChar(this);
					}
				}
			})
		}
		return this;
	}
})(jQuery);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zhou.tools.fileselector" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
    </application>

</manifest>


text:
<?php
/**
 * Qafoo PHP Refactoring Browser
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to kontakt@beberlei.de so I can send you a copy immediately.
 */

namespace QafooLabs\Refactoring\Application;

use QafooLabs\Refactoring\Domain\Model\Directory;
use QafooLabs\Refactoring\Domain\Model\File;
use QafooLabs\Refactoring\Domain\Model\PhpClassName;
use QafooLabs\Refactoring\Domain\Model\PhpName;

class OptimizeUse
{
    private $codeAnalysis;
    private $editor;
    private $phpNameScanner;

    public function __construct($codeAnalysis, $editor, $phpNameScanner)
    {
        $this->codeAnalysis = $codeAnalysis;
        $this->editor = $editor;
        $this->phpNameScanner = $phpNameScanner;
    }

    public function refactor(File $file)
    {
        $classes = $this->codeAnalysis->findClasses($file);
        $occurances = $this->phpNameScanner->findNames($file);
        $class = $classes[0];

        $appendNewLine = 0 === $class->namespaceDeclarationLine();
        $lastUseStatementLine = $class->namespaceDeclarationLine() + 2;
        $usedNames = array();
        $fqcns = array();

        foreach ($occurances as $occurance) {
            $name = $occurance->name();

            if ($name->type() === PhpName::TYPE_NAMESPACE || $name->type() === PhpName::TYPE_CLASS) {
                continue;
            }

            if ($name->isUse()) {
                $lastUseStatementLine = $occurance->declarationLine();
                $usedNames[] = $name->fullyQualifiedName();
            } elseif ($name->isFullyQualified()) {
                $fqcns[] = $occurance;
            }
        }

        if (!$fqcns) {
            return;
        }

        $buffer = $this->editor->openBuffer($file);

        foreach ($fqcns as $occurance) {
            $name = $occurance->name();
            $buffer->replaceString($occurance->declarationLine(), '\\'.$name->fullyQualifiedName(), $name->shortname());

            if (!in_array($name->fullyQualifiedName(), $usedNames)) {
                $lines = array(sprintf('use %s;', $name->fullyQualifiedName()));
                if ($appendNewLine) {
                    $appendNewLine = FALSE;
                    $lines[] = '';
                }

                $buffer->append($lastUseStatementLine, $lines);
                $lastUseStatementLine++;
            }
        }

        $this->editor->save();
    }
}


text:
require 'digest/sha1'
require 'activefacts/metamodel'
require 'activefacts/metamodel/datatypes'
require 'activefacts/compositions'
require 'activefacts/compositions/names'
require 'activefacts/generator'
require 'activefacts/generator/traits/expr'

module ActiveFacts
  module Generators
    module Traits
      module SQL
        MM = ActiveFacts::Metamodel unless const_defined?(:MM)

        # Options available in this flavour of SQL
        def options
          {
            keywords: ['Boolean', "Quote all keywords, not just reserved words"],
            restrict: ['String', "Restrict generation to tables in the specified group (e.g. bdv, rdv)"],
            joiner: ['String', "Use 'str' instead of the default joiner between words in table and column names"],
            unicode: ['Boolean', "Use Unicode for all text fields by default"],
            tables: [%w{cap title camel snake shout}, "Case to use for table names"],
            columns: [%w{cap title camel snake shout}, "Case to use for table names"],
            surrogates: [%w{counter guid hash}, "Method to use for assigning surrogate keys"],
            fks: [%w{no yes delay}, "Emit foreign keys, delay them to the end, or omit them"],
            # Legacy: datavault: ['String', "Generate 'raw' or 'business' data vault tables"],
          }
        end

        def compatibility
          [1, %i{relational}]
        end

        # The options parameter overrides any default options set by sub-traits
        def defaults_and_options options
          options
        end

        def process_options options
          @options = defaults_and_options options

          @quote_keywords = {nil=>true, 't'=>true, 'f'=>false, 'y'=>true, 'n'=>false}[@options.delete 'keywords']
          @quote_keywords = false if @keywords == nil  # Set default
          case (@options.delete "fks" || true)
          when true, '', 't', 'y', 'yes'
            @fks = true
          when 'd', 'delay'
            @fks = true
            @delay_fks = true
          when false, 'f', 'n', 'no'
            @fks = false
          end
          @unicode = @options.delete "unicode"
          @restrict = @options.delete "restrict"
          @surrogate_method = @options.delete('surrogates') || 'counter'
          raise "Unknown surrogate assignment method" unless %w{counter guid hash}.include?(@surrogate_method)

          # Name configuration options:
          @joiner = @options.delete('joiner')
          @table_joiner = @options.has_key?('tables') ? @joiner : nil
          @table_case = ((@options.delete('tables') || 'cap') + 'words').to_sym
          @table_joiner ||= [:snakewords, :shoutwords].include?(@table_case) ? '_' : ''
          @column_joiner = @options.has_key?('columns') ? @joiner : nil
          @column_case = ((@options.delete('columns') || 'cap') + 'words').to_sym
          @column_joiner ||= [:snakewords, :shoutwords].include?(@column_case) ? '_' : ''

          # Legacy option. Use restrict=bdv/rdv instead
          @datavault = @options.delete "datavault"
          case @datavault
          when "business"
            @restrict = "bdv"
          when "raw"
            @restrict = "rdv"
          end

          # Do not (yet) expose the closed-world vs open world problem.
          # Closed World vs Open World uniqueness is a semantic issue,
          # and so is OW, CW or CW with negation for unary fact types.
          # We need an overall strategy for handling it.
          @closed_world_indices = false   # Allow for SQL Server's non-standard NULL indexing
        end

        def data_type_context
          @data_type_context ||= data_type_context_class.new(surrogate_method: @surrogate_method)
        end

        def data_type_context_class
          SQLDataTypeContext
        end

        def table_name_max
          1024
        end

        def column_name_max
          1024
        end

        def index_name_max
          1024
        end

        def schema_name_max
          1024
        end

        # Anything this flavour needs to prefix a schema:
        def schema_prefix
          ''
        end

        def index_kind(index)
          ''
        end

        def binary_surrogate(type_name, value_constraint, options)
          if options[:auto_assign] == 'hash'
            :hash
          elsif type_name =~ /^(guid|uuid)$/i
            options[:length] ||= 16
            if ![nil, ''].include?(options[:auto_assign])
              options.delete(:auto_assign)  # Don't auto-assign foreign keys
              :guid
            else
              :guid_fk
            end
          else
            false
          end
        end

        # Return SQL type and (modified?) length for the passed base type
        def choose_sql_type(type_name, value_constraint, component, options)
          case MM::DataType.intrinsic_type(type_name)
          when MM::DataType::TYPE_Boolean
            data_type_context.boolean_type

          when MM::DataType::TYPE_Integer
            # The :auto_assign key is set for auto-assigned types, but with a nil value in foreign keys
            length = options[:length]
            if options.has_key?(:auto_assign)
              options[:default] ||= ' GENERATED ALWAYS AS IDENTITY' if options[:auto_assign]
              length = data_type_context.default_autoincrement_length
              type_name = 'int'
            end
            if chosen = MM::DataType.choose_integer(type_name, length, value_constraint, data_type_context)
              options.delete(:length)
              chosen
            else  # No available integer seems to suit. Use the defined type and length
              type_name
            end

          when MM::DataType::TYPE_Real
            'FLOAT'

          when MM::DataType::TYPE_Decimal
            'DECIMAL'

          when MM::DataType::TYPE_Money
            'DECIMAL'

          when MM::DataType::TYPE_Char
            data_type_context.default_char_type

          when MM::DataType::TYPE_String
            data_type_context.default_varchar_type

          when MM::DataType::TYPE_Text
            options[:length] ||= 'MAX'
            data_type_context.default_text_type

          when MM::DataType::TYPE_Date
            'DATE'

          when MM::DataType::TYPE_Time
            'TIME'

          when MM::DataType::TYPE_DateTime
            'TIMESTAMP'

          when MM::DataType::TYPE_Timestamp
            'TIMESTAMP'

          when MM::DataType::TYPE_Binary
            # If it's a surrogate, that might change the length we use
            binary_surrogate(type_name, value_constraint, options)
            if options[:length]
              'BINARY'          # Fixed length
            else
              'VARBINARY'
            end
          else
            type_name
          end
        end

        # The Components passed as leaves are fields in a table.
        # Return an array of SQL field names.
        def safe_column_names leaves
          leaves.map &method(:safe_column_name)
        end

        # Return an Expression for the Component passed as leaf, optionally using a table or alias name
        def safe_column_expr leaf, table_prefix = ''
          column_name = safe_column_name(leaf)
          type_name, = leaf.data_type(data_type_context)
          type_num = MM::DataType.intrinsic_type(type_name)
          Expression.new(table_prefix+column_name, type_num, leaf.is_mandatory)
        end

        # Return an array of Expressions for the fields, optionally qualified with a table or alias name
        def safe_column_exprs leaves, use_table_name = nil
          leaves.map{|leaf| safe_column_expr(leaf, table_prefix(leaf, use_table_name))}
        end

        # Return the string to prefix a column expression with to qualify it with a table or alias name
        def table_prefix component, use_table_name = nil
          case use_table_name
          when false, nil
            ''
          when true
            safe_table_name(component)+'.'
          else
            use_table_name+'.'
          end
        end

        def create_or_replace(name, kind)
          # There's no standard SQL way to do this. Do it anyway.
          "CREATE OR REPLACE #{kind} #{name}"
        end

        # For an (array of) Expression, return expressions that have value "na" if NULL
        def coalesce exprs, na = "'NA'"
          return exprs.map{|expr| coalesce(expr)} if Array === exprs
          return exprs if exprs.is_mandatory
          Expression.new("COALESCE(#{exprs}, #{na})", exprs.type_num, true)
        end

        def reserved_words
          @reserved_words ||= %w{
            ABS ABSOLUTE ACTION ADD ALL ALLOCATE ALTER AND ANY ARE
            ARRAY ARRAY_AGG ARRAY_MAX_CARDINALITY AS ASC ASENSITIVE
            ASSERTION ASYMMETRIC AT ATOMIC AUTHORIZATION AVG BEGIN
            BEGIN_FRAME BEGIN_PARTITION BETWEEN BIGINT BINARY BIT
            BIT_LENGTH BLOB BOOLEAN BOTH BY CALL CALLED CARDINALITY
            CASCADE CASCADED CASE CAST CATALOG CEIL CEILING CHAR
            CHARACTER CHARACTER_LENGTH CHAR_LENGTH CHECK CLOB CLOSE
            COALESCE COLLATE COLLATION COLLECT COLUMN COMMIT CONDITION
            CONNECT CONNECTION CONSTRAINT CONSTRAINTS CONTAINS CONTINUE
            CONVERT CORR CORRESPONDING COUNT COVAR_POP COVAR_SAMP
            CREATE CROSS CUBE CUME_DIST CURRENT CURRENT_CATALOG
            CURRENT_DATE CURRENT_DEFAULT_TRANSFORM_GROUP CURRENT_PATH
            CURRENT_ROLE CURRENT_ROW CURRENT_SCHEMA CURRENT_TIME
            CURRENT_TIMESTAMP CURRENT_TRANSFORM_GROUP_FOR_TYPE
            CURRENT_USER CURSOR CYCLE DATALINK DATE DAY DEALLOCATE
            DEC DECIMAL DECLARE DEFAULT DEFERRABLE DEFERRED DELETE
            DENSE_RANK DEREF DESC DESCRIBE DESCRIPTOR DETERMINISTIC
            DIAGNOSTICS DISCONNECT DISTINCT DLNEWCOPY DLPREVIOUSCOPY
            DLURLCOMPLETE DLURLCOMPLETEONLY DLURLCOMPLETEWRITE DLURLPATH
            DLURLPATHONLY DLURLPATHWRITE DLURLSCHEME DLURLSERVER
            DLVALUE DO DOMAIN DOUBLE DROP DYNAMIC EACH ELEMENT ELSE
            ELSEIF END END-EXEC END_FRAME END_PARTITION EQUALS ESCAPE
            EVERY EXCEPT EXCEPTION EXEC EXECUTE EXISTS EXIT EXP
            EXTERNAL EXTRACT FALSE FETCH FILTER FIRST FIRST_VALUE
            FLOAT FLOOR FOR FOREIGN FOUND FRAME_ROW FREE FROM FULL
            FUNCTION FUSION GET GLOBAL GO GOTO GRANT GROUP GROUPING
            GROUPS HANDLER HAVING HOLD HOUR IDENTITY IF IMMEDIATE
            IMPORT IN INDICATOR INITIALLY INNER INOUT INPUT INSENSITIVE
            INSERT INT INTEGER INTERSECT INTERSECTION INTERVAL INTO
            IS ISOLATION ITERATE JOIN KEY LAG LANGUAGE LARGE LAST
            LAST_VALUE LATERAL LEAD LEADING LEAVE LEFT LEVEL LIKE
            LIKE_REGEX LN LOCAL LOCALTIME LOCALTIMESTAMP LOOP LOWER
            MATCH MAX MAX_CARDINALITY MEMBER MERGE METHOD MIN MINUTE
            MOD MODIFIES MODULE MONTH MULTISET NAMES NATIONAL NATURAL
            NCHAR NCLOB NEW NEXT NO NONE NORMALIZE NOT NTH_VALUE NTILE
            NULL NULLIF NUMERIC OCCURRENCES_REGEX OCTET_LENGTH OF
            OFFSET OLD ON ONLY OPEN OPTION OR ORDER OUT OUTER OUTPUT
            OVER OVERLAPS OVERLAY PAD PARAMETER PARTIAL PARTITION
            PERCENT PERCENTILE_CONT PERCENTILE_DISC PERCENT_RANK
            PERIOD PORTION POSITION POSITION_REGEX POWER PRECEDES
            PRECISION PREPARE PRESERVE PRIMARY PRIOR PRIVILEGES
            PROCEDURE PUBLIC RANGE RANK READ READS REAL RECURSIVE REF
            REFERENCES REFERENCING REGR_AVGX REGR_AVGY REGR_COUNT
            REGR_INTERCEPT REGR_R2 REGR_SLOPE REGR_SXX REGR_SXY
            REGR_SYY RELATIVE RELEASE REPEAT RESIGNAL RESTRICT RESULT
            RETURN RETURNS REVOKE RIGHT ROLLBACK ROLLUP ROW ROWS
            ROW_NUMBER SAVEPOINT SCHEMA SCOPE SCROLL SEARCH SECOND
            SECTION SELECT SENSITIVE SESSION SESSION_USER SET SIGNAL
            SIMILAR SIZE SMALLINT SOME SPACE SPECIFIC SPECIFICTYPE
            SQL SQLCODE SQLERROR SQLEXCEPTION SQLSTATE SQLWARNING
            SQRT START STATIC STDDEV_POP STDDEV_SAMP SUBMULTISET
            SUBSTRING SUBSTRING_REGEX SUCCEEDS SUM SYMMETRIC SYSTEM
            SYSTEM_TIME SYSTEM_USER TABLE TABLESAMPLE TEMPORARY THEN
            TIME TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TO TRAILING
            TRANSACTION TRANSLATE TRANSLATE_REGEX TRANSLATION TREAT
            TRIGGER TRIM TRIM_ARRAY TRUE TRUNCATE UESCAPE UNDO UNION
            UNIQUE UNKNOWN UNNEST UNTIL UPDATE UPPER USAGE USER USING
            VALUE VALUES VALUE_OF VARBINARY VARCHAR VARYING VAR_POP
            VAR_SAMP VERSIONING VIEW WHEN WHENEVER WHERE WHILE
            WIDTH_BUCKET WINDOW WITH WITHIN WITHOUT WORK WRITE XML
            XMLAGG XMLATTRIBUTES XMLBINARY XMLCAST XMLCOMMENT XMLCONCAT
            XMLDOCUMENT XMLELEMENT XMLEXISTS XMLFOREST XMLITERATE
            XMLNAMESPACES XMLPARSE XMLPI XMLQUERY XMLSERIALIZE XMLTABLE
            XMLTEXT XMLVALIDATE YEAR ZONE
          }
        end

        def key_words
          @key_words ||= %w{
            A ABSENT ACCORDING ADA ADMIN AFTER ALWAYS ASSIGNMENT
            ATTRIBUTE ATTRIBUTES BASE64 BEFORE BERNOULLI BLOCKED BOM
            BREADTH C CATALOG_NAME CHAIN CHARACTERISTICS CHARACTERS
            CHARACTER_SET_CATALOG CHARACTER_SET_NAME CHARACTER_SET_SCHEMA
            CLASS_ORIGIN COBOL COLLATION_CATALOG COLLATION_NAME
            COLLATION_SCHEMA COLUMNS COLUMN_NAME COMMAND_FUNCTION
            COMMAND_FUNCTION_CODE COMMITTED CONDITION_NUMBER
            CONNECTION_NAME CONSTRAINT_CATALOG CONSTRAINT_NAME
            CONSTRAINT_SCHEMA CONSTRUCTOR CONTENT CONTROL CURSOR_NAME
            DATA DATETIME_INTERVAL_CODE DATETIME_INTERVAL_PRECISION
            DB DEFAULTS DEFINED DEFINER DEGREE DEPTH DERIVED DISPATCH
            DOCUMENT DYNAMIC_FUNCTION DYNAMIC_FUNCTION_CODE EMPTY
            ENCODING ENFORCED EXCLUDE EXCLUDING EXPRESSION FILE FINAL
            FLAG FOLLOWING FORTRAN FS G GENERAL GENERATED GRANTED HEX
            HIERARCHY ID IGNORE IMMEDIATELY IMPLEMENTATION INCLUDING
            INCREMENT INDENT INSTANCE INSTANTIABLE INSTEAD INTEGRITY
            INVOKER K KEY_MEMBER KEY_TYPE LENGTH LIBRARY LIMIT LINK
            LOCATION LOCATOR M MAP MAPPING MATCHED MAXVALUE MESSAGE_LENGTH
            MESSAGE_OCTET_LENGTH MESSAGE_TEXT MINVALUE MORE MUMPS
            NAME NAMESPACE NESTING NFC NFD NFKC NFKD NIL NORMALIZED
            NULLABLE NULLS NUMBER OBJECT OCTETS OFF OPTIONS ORDERING
            ORDINALITY OTHERS OVERRIDING P PARAMETER_MODE PARAMETER_NAME
            PARAMETER_ORDINAL_POSITION PARAMETER_SPECIFIC_CATALOG
            PARAMETER_SPECIFIC_NAME PARAMETER_SPECIFIC_SCHEMA PASCAL
            PASSING PASSTHROUGH PATH PERMISSION PLACING PLI PRECEDING
            RECOVERY REPEATABLE REQUIRING RESPECT RESTART RESTORE
            RETURNED_CARDINALITY RETURNED_LENGTH RETURNED_OCTET_LENGTH
            RETURNED_SQLSTATE RETURNING ROLE ROUTINE ROUTINE_CATALOG
            ROUTINE_NAME ROUTINE_SCHEMA ROW_COUNT SCALE SCHEMA_NAME
            SCOPE_CATALOG SCOPE_NAME SCOPE_SCHEMA SECURITY SELECTIVE
            SELF SEQUENCE SERIALIZABLE SERVER SERVER_NAME SETS SIMPLE
            SOURCE SPECIFIC_NAME STANDALONE STATE STATEMENT STRIP
            STRUCTURE STYLE SUBCLASS_ORIGIN T TABLE_NAME TIES TOKEN
            TOP_LEVEL_COUNT TRANSACTIONS_COMMITTED TRANSACTIONS_ROLLED_BACK
            TRANSACTION_ACTIVE TRANSFORM TRANSFORMS TRIGGER_CATALOG
            TRIGGER_NAME TRIGGER_SCHEMA TYPE UNBOUNDED UNCOMMITTED
            UNDER UNLINK UNNAMED UNTYPED URI USER_DEFINED_TYPE_CATALOG
            USER_DEFINED_TYPE_CODE USER_DEFINED_TYPE_NAME
            USER_DEFINED_TYPE_SCHEMA VALID VERSION WHITESPACE WRAPPER
            XMLDECLARATION XMLSCHEMA YES
          }
        end

        def is_reserved_word w
          @reserved_word_hash ||=
            ( reserved_words +
              (@quote_keywords ? key_words : [])).
            inject({}) do |h,w|
              h[w] = true
              h
            end
          @reserved_word_hash[w.upcase]
        end

        def go s = ''
          "#{s.sub(/\A\n+/,'')};\n"
        end

        def sql_value(value)
          value.is_literal_string ? sql_string(value.literal) : value.literal
        end

        def sql_string(str)
          "'" + str.gsub(/'/,"''") + "'"
        end

        def open_escape
          '"'
        end

        def close_escape
          '"'
        end

        def escape s, max = table_name_max
          # Escape SQL keywords and non-identifiers
          if s.size > max
            excess = s[max..-1]
            s = s[0...max-(excess.size/8)] +
              Digest::SHA1.hexdigest(excess)[0...excess.size/8]
          end

          if s =~ /[^A-Za-z0-9_]/ || is_reserved_word(s)
            "#{open_escape}#{s}#{close_escape}"
          else
            s
          end
        end

        def safe_table_name composite
          escape(table_name(composite), table_name_max)
        end

        def safe_column_name component
          escape(column_name(component), column_name_max)
        end

        def schema_name composition = @composition
          composition.name.words.send(@table_case)*@table_joiner
        end

        def table_name composite
          composite.mapping.name.words.send(@table_case)*@table_joiner
        end

        def column_name component
          words = component.column_name.send(@column_case)
          words*@column_joiner
        end

        def check_clause column_name, value_constraint
          " CHECK(" +
            value_constraint.all_allowed_range_sorted.map do |ar|
              vr = ar.value_range
              min = vr.minimum_bound
              max = vr.maximum_bound
              if (min && max && max.value.literal == min.value.literal)
                "#{column_name} = #{sql_value(min.value)}"
              else
                inequalities = [
                  min && "#{column_name} >#{min.is_inclusive ? "=" : ""} #{sql_value(min.value)}",
                  max && "#{column_name} <#{max.is_inclusive ? "=" : ""} #{sql_value(max.value)}"
                ].compact
                inequalities.size > 1 ? "(" + inequalities*" AND " + ")" : inequalities[0]
              end
            end*" OR " +
          ")"
        end

        class SQLDataTypeContext < MM::DataType::Context
          def initialize options = {}
            @surrogate_method = options.delete(:surrogate_method) || "counter"
            super
          end

          def integer_ranges
            [
              ['SMALLINT', -2**15, 2**15-1],  # The standard says -10^5..10^5 (less than 16 bits)
              ['INTEGER', -2**31, 2**31-1],   # The standard says -10^10..10^10 (more than 32 bits!)
              ['BIGINT', -2**63, 2**63-1],    # The standard says -10^19..10^19 (less than 64 bits)
            ]
          end

          def default_length data_type, type_name
            case data_type
            when MM::DataType::TYPE_Real
              53        # IEEE Double precision floating point
            when MM::DataType::TYPE_Integer
              case type_name
              when /([a-z ]|\b)Tiny([a-z ]|\b)/i
                8
              when /([a-z ]|\b)Small([a-z ]|\b)/i,
                /([a-z ]|\b)Short([a-z ]|\b)/i
                16
              when /([a-z ]|\b)Big(INT)?([a-z ]|\b)/i
                64
              else
                32
              end
            else
              nil
            end
          end

          # Note that BOOLEAN is an optional data type in SQL99.
          # Official literals are TRUE, FALSE and UNKNOWN.
          # Almost nothing (except Postgres) implements BOOLEAN, and
          # even that doesn't implement UNKNOWN (which works like NULL)
          def boolean_type
            'BOOLEAN'
          end

          # safe_column_name is an expression which yields boolean_type.
          # We use boolean_expr when we want to use it in a conditional context.
          def boolean_expr safe_column_name
            safe_column_name
          end

          def hash_type
            ['BINARY', {length: 32, auto_assign: 'hash' }]
          end

          # What type to use for a Metamodel::SurrogateKey
          def surrogate_type
            case @surrogate_method
            when 'guid'
              ["GUID", {auto_assign: 'guid'}]
            when 'hash'
              hash_type
            else  # counter
              type_name, min, max, length = choose_integer_range(0, 2**(default_autoincrement_length-1)-1)
              type_name
            end
          end

          def date_time_type
            'TIMESTAMP'
          end

          def default_char_type
            (@unicode ? 'NATIONAL ' : '') +
            'CHARACTER'
          end

          def default_varchar_type
            (@unicode ? 'NATIONAL ' : '') +
            'VARCHAR'
          end

          # Number of bits in an auto-counter
          def default_autoincrement_length
            64
          end

          def default_text_type
            default_varchar_type
          end
        end

      end
    end
  end
end


text:
+++
draft = false
image = "https://res.cloudinary.com/hpiynhbhq/image/upload/v1511635349/frzguqqicsgasvxcslwu.jpg"
showonlyimage = false
date = "2017-11-25T20:55:00"
title = "SteemConnect v2"
weight = 10
steem = "utopian-io/@roxane/steemconnect-accede-a-toutes-les-applications-utilisants-la-blockchain-steem-en-un-clic"
author = "@roxane"
+++

Accède à toutes les applications utilisants la blockchain Steem en un clic.

<!--more-->


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Allg. Gartenzeitung 18:41. 1850

#### Original name
null

### Remarks
null


text:
v<!DOCTYPE html>

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

    <meta name="description" content="Notes on Data Science, Machine Learning, & Artificial Intelligence">
    <meta name="author" content="Chris Albon">
    <link rel="icon" href="../favicon.ico">

    <title>Make Numbers Pretty - Scala</title>

    <link rel="stylesheet" href="../theme/css/bootstrap.css" />

    <link rel="stylesheet" type="text/css" href="../theme/css/ie10-viewport-bug-workaround.css" />

    <link rel="stylesheet" type="text/css" href="../theme/css/style.css" />
    <link rel="stylesheet" type="text/css" href="../theme/css/notebooks.css" />
    <link href='https://fonts.googleapis.com/css?family=PT+Serif:400,700|Roboto:400,500,700' rel='stylesheet' type='text/css'>

     <link href="http://runningthenumbers.co.uk/feeds/all.rss.xml" type="application/rss+xml" rel="alternate" title="Running the Numbers | Data Science Notes and Resources Full RSS Feed" />         <link href="http://runningthenumbers.co.uk/feeds/scala.rss.xml" type="application/rss+xml" rel="alternate" title="Running the Numbers | Data Science Notes and Resources Categories RSS Feed" />

    <meta name="tags" content="Basics" />

    <meta name="google-site-verification" content="7RLmddm4HbzdQLpwH2LH94_vBNmcaMGZSEhmmF5n0NM" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                Running The Numbers

                      ML/AI Notes

Blog

Machine Learning

Deep Learning

Algorithms

Python

Statistics

Cloud Computing

Javascript

SQL

Scala

Regex

Mathematics

                        About

About Chris

GitHub

Twitter

LinkedIn

Pinboard

                <form class="navbar-form" action="../search.html" onsubmit="return validateForm(this.elements['q'].value);">

                            <input class="form-control search-query" name="q" id="tipue_search_input" placeholder="e.g. scikit KNN, pandas merge" required autocomplete="off" type="text">

                </form>

    Want to learn machine learning? Use my machine learning flashcards.

      Make Numbers Pretty

        <time class="published" datetime="2017-01-03T12:00:00+00:00">
            03 January 2017
        </time>

Scala

Basics

This tutorial was inspired by the awesome Scala Cookbook.

Load The NumberFormat Library

// Make value that is assigned to an instance of numberformat
val make_pretty = java.text.NumberFormat.getInstance

Make An Integer Pretty

// Format 10000 to 10,000
make_pretty.format(10000)

Make A Float Pretty

// Format to 10000.1928 to 10,000.193
make_pretty.format(10000.1928)

10,000.193

Load The NumberFortmat Library Set For European Numbers

// Set the locale to germany
val germany = new java.util.Locale("de", "DE")

// Make value that is assigned to an instance of numberformat set to germany
val make_pretty_de = java.text.NumberFormat.getIntegerInstance(germany)

Make An Integer Pretty

// Format 1000000 to 1.000.000
make_pretty_de.format(1000000)

1.000.000

Find an error or bug?

Everything on this site is available on GitHub. Head to and submit a suggested change. You can also message me directly on Twitter.

                This project contains 486 pages and is available on GitHub.

                Copyright © Chris Albon,
                    <time datetime="2017">2017</time>.


text:
package org.omg.dds.core.policy;

import java.util.concurrent.TimeUnit;

import org.omg.dds.core.Duration;

/**
 * Specifies the maximum duration of validity of the data written by the
 * {@link org.omg.dds.pub.DataWriter}. The default value of the lifespan duration is infinite.
 *
 * Concerns: {@link org.omg.dds.topic.Topic}, {@link org.omg.dds.pub.DataWriter}
 *
 * RxO: N/A
 *
 * Changeable: Yes
 *
 * The purpose of this QoS is to avoid delivering "stale" data to the
 * application.
 *
 * Each data sample written by the DataWriter has an associated "expiration
 * time" beyond which the data should not be delivered to any application.
 * Once the sample expires, the data will be removed from the DataReader
 * caches as well as from the transient and persistent information caches.
 *
 * The "expiration time" of each sample is computed by adding the duration
 * specified by the LIFESPAN QoS to the source time stamp. As described in
 * {@link org.omg.dds.pub.DataWriter#write(Object)} and
 * {@link org.omg.dds.pub.DataWriter#write(Object, org.omg.dds.core.Time)}, the source time
 * stamp is either automatically computed by the Service each time the
 * write operation is called, or else supplied by the application.
 *
 * This QoS relies on the sender and receiving applications having their
 * clocks sufficiently synchronized. If this is not the case and the Service
 * can detect it, the DataReader is allowed to use the reception time stamp
 * instead of the source time stamp in its computation of the "expiration
 * time."
 */
public interface Lifespan
extends QosPolicy.ForTopic, QosPolicy.ForDataWriter
{
    public Duration getDuration();

    // --- Modification: -----------------------------------------------------

    /**
     * Copy this policy and override the value of the property.
     *
     * @return  a new policy
     */
    public Lifespan withDuration(Duration duration);

    /**
     * Copy this policy and override the value of the property.
     *
     * @return  a new policy
     */
    public Lifespan withDuration(long duration, TimeUnit unit);
}


text:
namespace ppapi_proxy {

// Implements the trusted side of the PPP_Zoom_Dev interface.
class BrowserZoom {
 public:
  static const PPP_Zoom_Dev* GetInterface();

 private:
  NACL_DISALLOW_COPY_AND_ASSIGN(BrowserZoom);
};

}  // namespace ppapi_proxy

#endif  // NATIVE_CLIENT_SRC_SHARED_PPAPI_PROXY_BROWSER_PPP_ZOOM_H_


text:
<template containerless bindable="router">

Aurelia Vote

</template>


text:
require 'gooddata_connectors_metadata/version'
require 'mongo'
require 'json'
require 'gooddata'

require_relative 'gooddata_connectors_metadata/metadata'
require_relative 'gooddata_connectors_metadata/runtime'

# TODO: List files in directory
%w(metadata_exception missing_parameters entity_exception type_exception).each { |file| require_relative "gooddata_connectors_metadata/exceptions/#{file}" }

# TODO: List files in directory
%w(metadata_exception missing_parameters).each { |file| require_relative "gooddata_connectors_metadata/exceptions/#{file}" }

# TODO: List files in directory
%w(entities entity field validation).each { |file| require_relative "gooddata_connectors_metadata/entity/#{file}" }

# TODO: List files in directory
%w(base boolean date decimal integer string).each { |file| require_relative "gooddata_connectors_metadata/types/#{file}" }
require_relative 'gooddata_connectors_metadata/configuration/configuration'

module GoodData
  module Connectors
    module Metadata
      class MetadataMiddleware < Bricks::Middleware
        def call(params)
          $log = params['GDC_LOGGER']

          $log.info 'Initilizing metadata storage'
          metadata = Metadata.new(params)
          # This section will handle default metadata load

          fail MetadataException, 'The variable SCHEDULE_ID is not present in metadata initialization call' if params['SCHEDULE_ID'].nil?

          # TODO: Eliminate $SCHEDULE_ID global variable
          $SCHEDULE_ID = params['SCHEDULE_ID']
          if $SCHEDULE_ID
            $log.info "Loading global metadata for schedule #{$SCHEDULE_ID}"
            metadata.load_global_hash($SCHEDULE_ID)
          end
          @app.call(params.merge!("metadata_wrapper" => metadata))
        end
      end
    end
  end
end


text:
//*********************************************************
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License"");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
// OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language
// governing permissions and limitations under the License.
//*********************************************************

using Microsoft.Live;
using OneNoteCloudCreatePagesSample.Common;
using Windows.UI.Xaml;

namespace OneNoteCloudCreatePagesSample
{
    /// <summary>
    /// Reepresents a settings flyout for handlign account sign in/sign out
    /// </summary>
    public sealed partial class AccountFlyout : SettingsFlyout
    {
        public static readonly DependencyProperty SignInNameProperty =
            DependencyProperty.Register("SignInName", typeof (string), typeof (AccountFlyout),
                                        new PropertyMetadata(null));

        public static readonly DependencyProperty IsSignedInProperty =
            DependencyProperty.Register("IsSignedIn", typeof(bool), typeof(AccountFlyout),
                                        new PropertyMetadata(null));
        /// <summary>
        /// Name shown as currently signed in user
        /// </summary>
        public string SignInName
        {
            get { return (string)this.GetValue(SignInNameProperty); }
            set { this.SetValue(SignInNameProperty, value); }
        }

        /// <summary>
        /// Is the user currently signed in
        /// </summary>
        public bool IsSignedIn
        {
            get { return (bool)this.GetValue(IsSignedInProperty); }
            set { this.SetValue(IsSignedInProperty, value); }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public AccountFlyout()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Opportunity to do flyout-specific logic when it the flyout is opened
        /// </summary>
        protected override void OnOpening()
        {
            base.OnOpening();
            this.UpdateState();
        }

        /// <summary>
        /// Click handler for sign in button
        /// </summary>
        private async void SignInClick(object sender, RoutedEventArgs e)
        {
            try
            {
                await MainPage.Current.SignIn();
                this.UpdateState();
            }
            catch (LiveConnectException)
            {
                // Handle exception.
            }
        }

        /// <summary>
        /// Click handler for sign out button
        /// </summary>
        private async void SignOutClick(object sender, RoutedEventArgs e)
        {
            try
            {
                await MainPage.Current.SignOut();
                this.UpdateState();
            }
            catch (LiveConnectException)
            {
                // Handle exception.
            }
        }

        /// <summary>
        /// Update the UI state to match the live status
        /// </summary>
        public void UpdateState()
        {
            try
            {
                this.SignInName = MainPage.Current.SignInName;
                this.IsSignedIn = MainPage.Current.IsSignedIn;
                if (this.IsSignedIn)
                {
                    // Show sign-out button if they can sign out.
                    signOutBtn.Visibility = (MainPage.Current.AuthClient.CanLogout
                                                 ? Visibility.Visible
                                                 : Visibility.Collapsed);
                    signInBtn.Visibility = Visibility.Collapsed;
                }
                else
                {
                    // Show sign-in button.
                    signInBtn.Visibility = Visibility.Visible;
                    signOutBtn.Visibility = Visibility.Collapsed;
                }
            }
            catch (LiveConnectException)
            {
                // Handle exception.
            }
        }
    }
}


text:
using System.Net.Http;
using System.Threading;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NerdBudget.Tests
{
    /// <summary>
    /// Helper Extensions for Testing API Controllers using Reduced Payload Manager
    /// </summary>
    /// <remarks>
    /// <code>
    /// <![CDATA[
    ///     //		arrange...
    ///
    ///     var settings = PayloadManager.AddPayload<Account>("Id", "Name").ToSettings();
    ///
    ///     //		act...
    ///     var result = SubjectUnderTest.GetAll();
    ///
    ///     var response = result.ExecuteAsync(CancellationToken.None);
    ///
    ///     response.Wait();
    ///
    ///     //		assert...
    ///     Assert.IsTrue(response.Result.IsSuccessStatusCode);
    ///
    ///     var actual = response.Result.Content.AssertJsonArrayEquality(
    ///
    ///     var expected = accounts.ToJsonArray(settings);
    ///
    ///     Assert.IsTrue(JToken.DeepEquals(actual, expected));
    /// ]]>
    /// </code>
    /// </remarks>
    static class JsonTestExtensions
    {
        #region Message

        public static HttpResponseMessage ToMessage(this IHttpActionResult results)
        {
            var response = results.ExecuteAsync(CancellationToken.None);

            response.Wait();

            return response.Result;
        }

        #endregion

        #region JArray

        private static JArray ToJsonArray(this HttpContent content)
        {
            var json = content.ReadAsStringAsync().Result;

            var actual = JsonConvert.DeserializeObject(json) as JArray;

            Assert.IsNotNull(actual, "Expected JArray on deserialize");

            return actual;
        }

        private static JArray ToJsonArray<T>(this T expected, JsonSerializerSettings settings)
        {
            var json = JsonConvert.SerializeObject(expected, settings);

            var array = JsonConvert.DeserializeObject(json) as JArray;

            Assert.IsNotNull(array, "Expected JArray on deserialize");

            return array;
        }

        #endregion

        #region JObject

        private static JObject ToJsonObject(this HttpContent content)
        {
            var json = content.ReadAsStringAsync().Result;

            var actual = JsonConvert.DeserializeObject(json) as JObject;

            return actual;
        }

        private static JObject ToJsonObject<T>(this T expected, JsonSerializerSettings settings)
        {
            var json = JsonConvert.SerializeObject(expected, settings);

            return JsonConvert.DeserializeObject(json) as JObject;
        }

        #endregion

        #region Assert Equality

        public static void AssertJsonArrayEquality<T>(this HttpContent content, T expected, JsonSerializerSettings expectedSettings)
        {
            var actualJson = content.ToJsonArray();

            var expectedJson = expected.ToJsonArray(expectedSettings);

            Assert.IsTrue(JToken.DeepEquals(actualJson, expectedJson));
        }

        public static void AssertJsonObjectEquality<T>(this HttpContent content, T expected, JsonSerializerSettings expectedSettings)
        {
            var actualJson = content.ToJsonObject();

            var expectedJson = expected.ToJsonObject(expectedSettings);

            Assert.IsTrue(JToken.DeepEquals(actualJson, expectedJson));
        }

        #endregion
    }
}


text:
// Copyright 2005 The Apache Software Foundation
//
// 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 org.ops4j.gaderian.management.mbeans;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;

import org.ops4j.gaderian.management.mbeans.AbstractDynamicMBean;

/**
 * Test MBean
 *
 * @author Achim Huegen
 */
public class ConcreteMBean extends AbstractDynamicMBean
{
    private String attribute1 = "value1";

    private String attribute2 = "value2";

    public boolean isSetAttribute1Called;

    public boolean isSetAttribute2Called;

    public ConcreteMBean()
    {
    }

    protected MBeanAttributeInfo[] createMBeanAttributeInfo()
    {
        MBeanAttributeInfo att1 = new MBeanAttributeInfo("attribute1", "String", "", true,
                true, false);
        MBeanAttributeInfo att2 = new MBeanAttributeInfo("attribute2", "String", "", true,
                true, false);
        return new MBeanAttributeInfo[]
        { att1, att2 };
    }

    protected MBeanConstructorInfo[] createMBeanConstructorInfo()
    {
        MBeanConstructorInfo constructor = new MBeanConstructorInfo("constructor", "",
                new MBeanParameterInfo[] {});
        return new MBeanConstructorInfo[]
        { constructor };
    }

    protected MBeanNotificationInfo[] createMBeanNotificationInfo()
    {
        MBeanNotificationInfo notification = new MBeanNotificationInfo(new String[0],
                "notification", "");
        return new MBeanNotificationInfo[]
        { notification };
    }

    protected MBeanOperationInfo[] createMBeanOperationInfo()
    {
        MBeanOperationInfo operation = new MBeanOperationInfo("operation", "",
                new MBeanParameterInfo[0], "String", 0);
        return new MBeanOperationInfo[]
        { operation };
    }

    public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException,
            ReflectionException
    {
        if (name.equals("attribute1"))
            return attribute1;
        if (name.equals("attribute2"))
            return attribute2;
        throw new AttributeNotFoundException();
    }

    public void setAttribute(Attribute attribute) throws AttributeNotFoundException,
            InvalidAttributeValueException, MBeanException, ReflectionException
    {
        if (attribute.getName().equals("attribute1"))
            attribute1 = (String) attribute.getValue();
        if (attribute.getName().equals("attribute2"))
            attribute2 = (String) attribute.getValue();
        throw new AttributeNotFoundException();
    }
}


text:
package org.apache.wicket.util.tester;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 * WICKET-3053
 *
 * Clicking AjaxSubmitLink does not preserve the values of the form components and they get
 * null-ified
 *
 *
 * The code is borrowed from Wicket+Guice LegUp (http://jweekend.com/dev/LegUp)
 *
 * @author Richard Wilkinson - richard.wilkinson@jweekend.com
 */
public class MockPageAjaxSubmitLinkSubmitsWholeForm extends WebPage
{
	private static final long serialVersionUID = 1L;

	private String text;

	private String name;

	/**
	 * Constructor that is invoked when page is invoked without a em.
	 *
	 * @param parameters
	 *            Page parameters
	 */
	public MockPageAjaxSubmitLinkSubmitsWholeForm(final PageParameters parameters)
	{
		final Label label = new Label("text", new PropertyModel<String>(this, "text"));
		label.setOutputMarkupId(true);

		add(label);

		Form<Void> form = new Form<Void>("form");
		form.add(new TextField<String>("name", new PropertyModel<String>(this, "name")));

		add(form);

		add(new AjaxSubmitLink("helloSubmit", form)
		{

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target)
			{
				text = "Hello " + name;
				target.add(label);
			}

			@Override
			protected void onError(AjaxRequestTarget target)
			{
				throw new RuntimeException("Unexpected error occurred.");
			}
		});

		add(new AjaxSubmitLink("goodbyeSubmit", form)
		{

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target)
			{
				text = "Goodbye " + name;
				target.add(label);
			}

			@Override
			protected void onError(AjaxRequestTarget target)
			{
				throw new RuntimeException("Unexpected error occurred.");
			}
		});

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


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

public class Vowel_or_Digit
{
    public static void Main()
    {
        var symbol = Convert.ToChar(Console.ReadLine());

        var vowels = new List<char>();
        vowels.Add('a');
        vowels.Add('e');
        vowels.Add('i');
        vowels.Add('o');
        vowels.Add('u');

        if (vowels.Contains(symbol))
        {
            Console.WriteLine("vowel");
        }

        else if ((symbol >= '0') && (symbol <= '9'))
        {
            Console.WriteLine("digit");
        }

        else
        {
            Console.Write("other");
        }
    }
}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Rule API key
    |--------------------------------------------------------------------------
    |
    | Here you may specify your Rule API key. This i needed for sending email
    | transactions with Rule.
    |
    */
    'api_key' => 'YOUR_API_KEY_HERE',

    /*
    |--------------------------------------------------------------------------
    | Slack webhook
    |--------------------------------------------------------------------------
    |
    | Here you may specify which incoming webhook to use.
    |
    */
    'slack_endpoint' => 'https://hook...',

    /*
    |--------------------------------------------------------------------------
    | Debug Mode
    |--------------------------------------------------------------------------
    |
    | Here you can specify weather to set debug mode on channels.
    | If debug is set to true, all notification messages will be logged to file.
    | Specify log file path below.
    |
    */
    'debug' => false,
    'log_path' => 'path/to/your.log'
];


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Yves\Application\Plugin\Provider;

use Silex\Application;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

class YvesSecurityServiceProvider extends AbstractServiceProvider
{
    public const BCRYPT_FACTOR = 12;

    /**
     * @param \Silex\Application $app
     *
     * @return void
     */
    public function register(Application $app)
    {
        $app['security.encoder.digest'] = function ($app) {
            return new BCryptPasswordEncoder(self::BCRYPT_FACTOR);
        };
    }

    /**
     * @param \Silex\Application $app
     *
     * @return void
     */
    public function boot(Application $app)
    {
    }
}


text:
[![default_img]][statuses]
[![darcula_img]][statuses]
[![darker_img]][statuses]

[![lighter_img]][statuses]

[![plugin_img]][plugin_link]
[![android_arsenal_img]][android_arsenal_link]
[![license_img]][license_link]
[![thanks_img]][thanks_link]

# ChroMATERIAL
ChroMATERIAL is a color scheme that expresses the chromatic nature of [Material Design][material] within JetBrain IDEs and Android Studio. In particular, ChroMATERIAL focuses on syntax highlighting of code within the IDE's code editor.

It's uniqueness lies in the idea...

> **Enhance influence, not banality**

![chromaterial_color-range_main][latest_img_normal]
**Note** these images contain code from [Google's Android Vision API][android-vision] barcode sample app.

# Support

| Type          | Supported |
| :-----------: | :-------- |
| **IDEs**      | Android Studio IntelliJ IDEA PyCharm  RubyMine WebStorm PhpStorm AppCode CLion DataGrip
ChroMATERIAL supports **Text Editor** changes only.
ChroMATERIAL + [Material Theme][chris-rm_theme] will modify the whole IDE! |
|               |           |
| **Languages** | Java Kotlin Groovy XML JSON HTML Regex YAML
 **Pull Requests** are welcome. |
|               |           |
| **Others**    | Android Android Manifest Android ResourcesAndroid Native (C / C++) Gradle Logcat Proguard Files Property Files Version Control Debugger Diff XSLT XPATH

 Support via Plugins
 Ignore Files Markdown

 **Pull Requests** are welcome. |

# Installation

**Find Plugin**
 1. Open IDE and locate File >> Settings >> Plugins and click [Browse Repositories...][browse-repo]
 2. Search for and click ChroMATERIAL and click [Install plugin][install-plugin]

**Use Color Scheme**

  3. Locate [File >> Settings >> Editor >> Color Scheme][use-plugin]
  4. Choose a color scheme from the drop-down menu and click Apply / OK.
 ChroMATERIAL ChroMATERIAL - Darker or ChroMATERIAL - Darcula

### Optional

You can modify any of the following in the code editor...

 - **font type** to your preference
 - **syntax highlighting** further to fit your particular tastes.

[yes]: https://cloud.githubusercontent.com/assets/8707125/10560554/6e30a660-7549-11e5-95ec-a07b0c049339.png
[no]: https://cloud.githubusercontent.com/assets/8707125/10560555/7263eddc-7549-11e5-8939-bfd2d6141f11.png
[information]: https://cloud.githubusercontent.com/assets/8707125/12080665/ebdfd2a0-b2a4-11e5-9419-53b5c41874d5.png
               "View meanings"

[latest_img_normal]: https://cloud.githubusercontent.com/assets/8707125/12482832/27668d52-c095-11e5-89e9-01bb67e65aba.PNG

[v2.1_img_normal]: #

[v2.0_img_normal]: #

[v1.2_img_normal]: #

[v1.1_img_normal]: https://cloud.githubusercontent.com/assets/8707125/12482832/27668d52-c095-11e5-89e9-01bb67e65aba.PNG

[v1.0_img_normal]: https://cloud.githubusercontent.com/assets/8707125/10559945/814a770c-7536-11e5-99d4-efd4d03ea3f5.PNG
[v1.0_img_range]: https://cloud.githubusercontent.com/assets/8707125/10559946/814af8bc-7536-11e5-8666-102db39305f0.PNG

[material]: http://www.google.co.kr/design/spec/material-design/introduction.html#
[android-vision]: https://github.com/googlesamples/android-vision
[chris-rm]: https://github.com/ChrisRM
[chris-rm_theme]: https://github.com/ChrisRM/material-theme-jetbrains

[browse-repo]: https://user-images.githubusercontent.com/8707125/30756120-3de0c354-a004-11e7-8653-d23a52eaabc7.png
[install-plugin]: https://user-images.githubusercontent.com/8707125/30756128-4a247d22-a004-11e7-9676-5e23a0e4a2a5.png
[use-plugin]: https://user-images.githubusercontent.com/8707125/30771281-a733fb12-a07e-11e7-9676-760a8cbe012c.png

[jar]: ChroMATERIAL/ChroMATERIAL.jar
[readme]: README.md
[statuses]: STATUS.md

[plugin_img]: https://img.shields.io/badge/JetBrain_Plugin_Repository-7998-green.svg?style=flat-square
[plugin_link]: https://plugins.jetbrains.com/plugin/7998

[android_arsenal_img]: https://img.shields.io/badge/Android%20Arsenal-3936-green.svg?style=flat-square
[android_arsenal_link]: https://android-arsenal.com/details/1/3936

[license_img]: https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square
[license_link]: LICENSE

[default_img]: https://img.shields.io/badge/Default_Color_Scheme-Complete-brightgreen.svg?style=flat-square
[darcula_img]: https://img.shields.io/badge/Darcula--compatible_Color_Scheme-Complete-brightgreen.svg?style=flat-square
[darker_img]: https://img.shields.io/badge/Darker_Color_Scheme-Complete-brightgreen.svg?style=flat-square
[lighter_img]: https://img.shields.io/badge/Lighter_Color_Scheme-Future-red.svg?style=flat-square

[thanks_img]: https://img.shields.io/badge/Special_Thanks-3-blue.svg?style=flat-square
[thanks_link]: THANKS.md


text: Church Office


text:
namespace boost {
  template<typename F> class function {};

  namespace graph {
    template<typename V, typename E> class adjacency_list { };
  };
}