text:
//
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "TressFXOpaqueVulkan.h"

namespace AMD
{
void TressFX_OpaqueDesc::Initialize(TressFX_Desc &desc,
                                    VkImageView depthTexture,
                                    VkImageView colorTexture,
                                    VkCommandBuffer commandBuffer,
                                    VkDeviceMemory scratchMemory,
                                    VkBuffer scratchBuffer,
                                    size_t &offsetInScratchBuffer,
                                    VkPhysicalDeviceMemoryProperties memProperties)
{
    refCount = 0;
    markerCallbacks.init(desc.pvkDevice);
    tressFXSimulation.OnCreateDevice(desc.pvkDevice,
                                        &desc.collisionCapsule,
                                        desc.maxConstantBuffers, memProperties,
                                        markerCallbacks);
    tressFXRenderer.OnCreateDevice(
        desc.pvkDevice, desc.backBufferWidth, desc.backBufferHeight, desc.bShortCutOn,
        desc.maxConstantBuffers, memProperties,
        depthTexture, colorTexture, commandBuffer, scratchMemory, scratchBuffer,
        offsetInScratchBuffer, desc.depthStencilFormat, desc.colorFormat);
    refCount++;
}

void TressFX_OpaqueDesc::Release(VkDevice pvkDevice)
{
    refCount--;
    if (refCount <= 0)
    {
        tressFXRenderer.OnDestroy();
        tressFXSimulation.OnDestroy(pvkDevice);
        refCount = 0;
    }
}

bool TressFX_OpaqueDesc::LoadAppendAsset(
    TressFX_HairBlob *pRawHairBlob, const TressFX_GuideFollowParams &guideFollowParams,
    int groupId)
{
    return tressFXAssetLoader.LoadAppend(pRawHairBlob, guideFollowParams, groupId);
}

bool TressFX_OpaqueDesc::CreateProcessedAsset(
    TressFX_Desc &desc, TressFX_HairBlob **ppHairBlob, TressFX_SceneMesh *sceneMesh,
    VkImageView hairTexture, VkPhysicalDeviceMemoryProperties memProperties,
    VkCommandBuffer uploadCmdBuffer, VkBuffer scratchBuffer, VkDeviceMemory scratchMemory)
{
    tressFXAssetLoader.GenerateFollowHairs();
    tressFXAssetLoader.ProcessVertices();

    if (desc.tressFXHair.pHair != NULL)
    {
        delete desc.tressFXHair.pHair;
        desc.tressFXHair.pHair = NULL;
        desc.tressFXHair.size = 0;
    }

    tressFXAssetLoader.Serialize(&desc.tressFXHair);

    TressFXMesh *pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
    if (pTressFXMesh != NULL)
    {
        delete pTressFXMesh;
    }
    pTressFXMesh = new TressFXMesh();
    pTressFXMesh->OnCreate(desc.pvkDevice, &desc.tressFXHair, sceneMesh,
                           hairTexture,
                           memProperties, uploadCmdBuffer,
                           scratchBuffer,
                           scratchMemory,
                           tressFXSimulation.m_GlobalConstraintsSetLayout,
                           tressFXSimulation.m_LocalConstraintsSetLayout,
                           tressFXSimulation.m_LenghtWindTangentSetLayout,
                           tressFXSimulation.m_PrepareFollowHairSetLayout,
                           tressFXSimulation.m_UpdateFollowHaitSetLayout,
                           desc.pOpaque->tressFXSimulation.m_ComputeTangentSetLayout,
                           tressFXRenderer.m_pass1_hair_set_layout,
                           tressFXRenderer.m_shadow_pass_hair_set_layout,
                           desc.pOpaque->markerCallbacks);

    desc.numTotalHairStrands = pTressFXMesh->m_HairAsset.m_NumTotalHairStrands;
    desc.numTotalHairVertices = pTressFXMesh->m_HairAsset.m_NumTotalHairVertices;
    desc.pTressFXMesh = (void *)pTressFXMesh;

    if (ppHairBlob != NULL)
    {
        *ppHairBlob = &desc.tressFXHair;
    }

    tressFXAssetLoader.Clear();

    return true;
}

bool TressFX_OpaqueDesc::Simulate(TressFX_Desc &desc, VkCommandBuffer commandBuffer,
                                  float elapsedTime, uint32_t uniformBufferIndex)
{
    tressFXSimulation.m_pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
    desc.numTotalHairStrands =
        tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairStrands;
    desc.numTotalHairVertices =
        tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairVertices;
    tressFXSimulation.SetSimulationParams(desc.simulationParams);
    tressfx_vec3 windDir;
    windDir.x = desc.simulationParams.windDir.x;
    windDir.y = desc.simulationParams.windDir.y;
    windDir.z = desc.simulationParams.windDir.z;
    VkResult vr = tressFXSimulation.Simulate(
        desc.pvkDevice, commandBuffer, elapsedTime, desc.hairParams.density, windDir,
        desc.simulationParams.windMag, &desc.modelTransformForHead,
        desc.targetFrameRate, desc.bSingleHeadTransform, false, uniformBufferIndex,
        markerCallbacks);

    return vr == VK_SUCCESS;
}

bool TressFX_OpaqueDesc::Begin(TressFX_Desc &desc, uint32_t uniformBufferIndex)
{
    tressFXRenderer.m_pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
    tressFXSimulation.m_pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
    desc.numTotalHairStrands =
        tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairStrands;
    desc.numTotalHairVertices =
        tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairVertices;
    tressFXRenderer.m_hairParams = desc.hairParams;
    tressFXRenderer.BeginHairFrame(
        desc.pvkDevice, desc.eyePoint, desc.lightPosition, &desc.modelTransformForHead,
        &desc.mViewProj, &desc.mViewProjLightFromLibrary, (float)desc.backBufferWidth,
        (float)desc.backBufferHeight, desc.bSingleHeadTransform, uniformBufferIndex);
    return true;
}

bool TressFX_OpaqueDesc::RenderShadowMap(TressFX_Desc &desc,
                                         VkCommandBuffer commandBuffer,
                                         uint32_t uniformBufferIndex)
{
    tressFXRenderer.GenerateShadowMap(desc.pvkDevice,
                                      commandBuffer,
                                      desc.hairParams.density, uniformBufferIndex,
                                      markerCallbacks);
    desc.pHairShadowMapSRV = tressFXRenderer.GetShadowMapSRV();
    return true;
}

bool TressFX_OpaqueDesc::RenderHair(TressFX_Desc &desc, VkCommandBuffer commandBuffer,
                                    uint32_t uniformBufferIndex)
{
    if (desc.bShortCutOn)
    {
        tressFXRenderer.RenderHairShortcut(desc.pvkDevice,
                                           commandBuffer,
                                           desc.backBufferWidth,
                                           desc.backBufferHeight,
                                           uniformBufferIndex, markerCallbacks);
    }
    else
    {
        tressFXRenderer.RenderHair(desc.pvkDevice, commandBuffer,
                                   desc.backBufferWidth,
                                   desc.backBufferHeight, uniformBufferIndex,
                                   markerCallbacks);
    }
    return true;
}

bool TressFX_OpaqueDesc::End(TressFX_Desc &desc)
{
    tressFXRenderer.EndHairFrame(desc.pvkDevice);
    return true;
}

bool TressFX_OpaqueDesc::Resize(TressFX_Desc &desc, VkPhysicalDeviceMemoryProperties memProperties)
{
    VkResult vr = tressFXRenderer.OnResizedSwapChain(
        desc.pvkDevice, desc.backBufferWidth, desc.backBufferHeight, desc.bShortCutOn,
		memProperties);
    return (vr == VK_SUCCESS);
}

bool TressFX_OpaqueDesc::GenerateTransforms(TressFX_Desc &desc,
                                            TressFX_SceneMesh &sceneMesh)
{
    (void)desc;
    (void)sceneMesh;
    /*        tressFXSimulation.m_pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
            desc.numTotalHairStrands =
       tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairStrands;
            desc.numTotalHairVertices =
       tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairVertices;
            HRESULT hr = tressFXSimulation.GenerateTransforms(desc.pd3dDeviceContext,
       sceneMesh,
                &desc.pSkinningTransformationsUAV, &desc.modelTransformForHead);
            return (hr == S_OK);*/
    return true;
}

bool TressFX_OpaqueDesc::ApplyRigidTransforms(TressFX_Desc &desc)
{
    (void)desc;
    /*        tressFXSimulation.m_pTressFXMesh = (TressFXMesh *)desc.pTressFXMesh;
            desc.numTotalHairStrands =
       tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairStrands;
            desc.numTotalHairVertices =
       tressFXSimulation.m_pTressFXMesh->m_HairAsset.m_NumTotalHairVertices;
                    HRESULT hr =
       tressFXSimulation.ApplyTransformGlobally(desc.pd3dDeviceContext,
       desc.pSkinningTransformationsUAV, desc.hairParams.density,
       desc.bSingleHeadTransform, &desc.modelTransformForHead);
            return (hr == S_OK);*/
    return true;
}

} // namespace AMD


text:
Template.home.helpers({
  votedClass: function() {
    //we can subscribe here because templates are reactive
    Meteor.subscribe('votes_from_user', Meteor.userId());
    return Meteor.user()
      ? Meteor.user().hasAlreadyVoted(this._id)
      ? 'orange'
      : 'green'
    : 'green';
  },
  isSelection: function() {
    return Competition.isSelection();
  }
});

Template.home.events({
  'click .vote-nominee': function(e) {
    e.preventDefault();
    if (!Meteor.user())
      Router.go('login',{}, {query: "next=home"});
    else
      Meteor.user().vote(this._id, 'web');
  },
  'click .comment-count':function(e,tmpl) {
      e.preventDefault();
      Router.go('nomineeProfile', {id: this._id}, {query: 'goto=comments-row'})
   },
  'keyup #homePageSearch': function() {
    var query = document.getElementById("homePageSearch").value.trim();
    Session.set('homeSearch', query);
  }
});

redpajama_set_name: RedPajamaGithub


text:
package com.hubspot.singularity.runner.base.jackson;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({ METHOD, FIELD, PARAMETER })
@Retention(RUNTIME)
public @interface Obfuscate {
}


text:
<test>
	<title>::first-line on inlines</title>

This line should be green.

</test>


text:
#include <stddef.h>
#include <linux/magic.h>
#include <btrfs/ioctl.h>
#include <btrfs/ctree.h>

#include "btrfs.h"

void unpack_root_item(struct gosafe_btrfs_root_item* dst, struct btrfs_root_item* src) {
	memcpy(dst->uuid, src->uuid, BTRFS_UUID_SIZE);
	memcpy(dst->parent_uuid, src->parent_uuid, BTRFS_UUID_SIZE);
	memcpy(dst->received_uuid, src->received_uuid, BTRFS_UUID_SIZE);
	dst->gen = btrfs_root_generation(src);
	dst->ogen = btrfs_root_otransid(src);
	dst->flags = btrfs_root_flags(src);
}

/* unpack_root_ref(struct gosafe_btrfs_root_ref* dst, struct btrfs_root_ref* src) { */


text:
package javax.crypto;

import java.security.GeneralSecurityException;

/**
 * This exception is thrown when an output buffer provided by the user
 * is too short to hold the operation result.
 *
 * @author Jan Luehe
 *
 * @since 1.4
 */

public class ShortBufferException extends GeneralSecurityException {

    private static final long serialVersionUID = 8427718640832943747L;

    /**
     * Constructs a ShortBufferException with no detail
     * message. A detail message is a String that describes this
     * particular exception.
     */
    public ShortBufferException() {
        super();
    }

    /**
     * Constructs a ShortBufferException with the specified
     * detail message.
     *
     * @param msg the detail message.
     */
    public ShortBufferException(String msg) {
        super(msg);
    }
}


text:
**Supplies needed:** Post-its, Sharpie, Whiteboard

**Estimated time:** 30 min

## Best to use when

Needs, Wants, Desires is a [Card Sorting](card-sorting.md)
exercise to help figure out priorities.
It's best to use when there are a lot of feature ideas
being thrown around when there isn't a good sense of which is the most
important.

## Instructions:

1. List out feature ideas on Post-its.
* Divide up the whiteboard into 3 sections: Needs, Wants, and Desires
* For the first feature,
add it to *Needs* if it is critical to the job to be done,
*Wants* if it is supplemental to the main job to be done,
*Desires* if it outside of the main job to be done.
It is best to reflect on the [Problem Statement](problem-statement.md)
while doing this.
* Repeat for each of the remaining ideas.
* Once all of the features are sorted,
look at each section and the features in them
and verify that each feature in is the appropriate section.

## Examples

![Needs, Wants, Desires](images/needs-wants-desires.jpg)


text:
package org.gingolph.gingmap.memory;

import org.gingolph.gingmap.RoleImpl;
import org.gingolph.gingmap.RoleSupport;
import org.gingolph.gingmap.TopicImpl;

public class IMRoleSupport extends IMConstructSupport implements RoleSupport {
  TopicImpl type;
  TopicImpl reifier;
  TopicImpl player;

  @Override
  public TopicImpl getType() {
    return type;
  }

  @Override
  public void setType(TopicImpl type) {
    this.type = type;
  }

  @Override
  public TopicImpl getReifier() {
    return reifier;
  }

  @Override
  public void setReifier(TopicImpl reifier) {
    this.reifier = reifier;
  }

  @Override
  public TopicImpl getPlayer() {
    return player;
  }

  @Override
  public void setPlayer(TopicImpl player) {
    this.player = player;
  }

  @Override
  public void setOwner(RoleImpl owner) {
 // Noop - not needed by the in memory implementation
  }
}


text:
/*
 *  Altera FPGA support
 */
#include <common.h>
#include <ACEX1K.h>
#include <stratixII.h>

/* Define FPGA_DEBUG to get debug printf's */
/* #define FPGA_DEBUG */

#ifdef	FPGA_DEBUG
#define	PRINTF(fmt,args...)	printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif

/* Local Static Functions */
static int altera_validate (Altera_desc * desc, const char *fn);

/* ------------------------------------------------------------------------- */
int altera_load(Altera_desc *desc, const void *buf, size_t bsize)
{
	int ret_val = FPGA_FAIL;	/* assume a failure */

	if (!altera_validate (desc, (char *)__FUNCTION__)) {
		printf ("%s: Invalid device descriptor\n", __FUNCTION__);
	} else {
		switch (desc->family) {
		case Altera_ACEX1K:
		case Altera_CYC2:
#if defined(CONFIG_FPGA_ACEX1K)
			PRINTF ("%s: Launching the ACEX1K Loader...\n",
					__FUNCTION__);
			ret_val = ACEX1K_load (desc, buf, bsize);
#elif defined(CONFIG_FPGA_CYCLON2)
			PRINTF ("%s: Launching the CYCLONE II Loader...\n",
					__FUNCTION__);
			ret_val = CYC2_load (desc, buf, bsize);
#else
			printf ("%s: No support for ACEX1K devices.\n",
					__FUNCTION__);
#endif
			break;

#if defined(CONFIG_FPGA_STRATIX_II)
		case Altera_StratixII:
			PRINTF ("%s: Launching the Stratix II Loader...\n",
				__FUNCTION__);
			ret_val = StratixII_load (desc, buf, bsize);
			break;
#endif
		default:
			printf ("%s: Unsupported family type, %d\n",
					__FUNCTION__, desc->family);
		}
	}

	return ret_val;
}

int altera_dump(Altera_desc *desc, const void *buf, size_t bsize)
{
	int ret_val = FPGA_FAIL;	/* assume a failure */

	if (!altera_validate (desc, (char *)__FUNCTION__)) {
		printf ("%s: Invalid device descriptor\n", __FUNCTION__);
	} else {
		switch (desc->family) {
		case Altera_ACEX1K:
#if defined(CONFIG_FPGA_ACEX)
			PRINTF ("%s: Launching the ACEX1K Reader...\n",
					__FUNCTION__);
			ret_val = ACEX1K_dump (desc, buf, bsize);
#else
			printf ("%s: No support for ACEX1K devices.\n",
					__FUNCTION__);
#endif
			break;

#if defined(CONFIG_FPGA_STRATIX_II)
		case Altera_StratixII:
			PRINTF ("%s: Launching the Stratix II Reader...\n",
				__FUNCTION__);
			ret_val = StratixII_dump (desc, buf, bsize);
			break;
#endif
		default:
			printf ("%s: Unsupported family type, %d\n",
					__FUNCTION__, desc->family);
		}
	}

	return ret_val;
}

int altera_info( Altera_desc *desc )
{
	int ret_val = FPGA_FAIL;

	if (altera_validate (desc, (char *)__FUNCTION__)) {
		printf ("Family:        \t");
		switch (desc->family) {
		case Altera_ACEX1K:
			printf ("ACEX1K\n");
			break;
		case Altera_CYC2:
			printf ("CYCLON II\n");
			break;
		case Altera_StratixII:
			printf ("Stratix II\n");
			break;
			/* Add new family types here */
		default:
			printf ("Unknown family type, %d\n", desc->family);
		}

		printf ("Interface type:\t");
		switch (desc->iface) {
		case passive_serial:
			printf ("Passive Serial (PS)\n");
			break;
		case passive_parallel_synchronous:
			printf ("Passive Parallel Synchronous (PPS)\n");
			break;
		case passive_parallel_asynchronous:
			printf ("Passive Parallel Asynchronous (PPA)\n");
			break;
		case passive_serial_asynchronous:
			printf ("Passive Serial Asynchronous (PSA)\n");
			break;
		case altera_jtag_mode:		/* Not used */
			printf ("JTAG Mode\n");
			break;
		case fast_passive_parallel:
			printf ("Fast Passive Parallel (FPP)\n");
			break;
		case fast_passive_parallel_security:
			printf
			    ("Fast Passive Parallel with Security (FPPS) \n");
			break;
			/* Add new interface types here */
		default:
			printf ("Unsupported interface type, %d\n", desc->iface);
		}

		printf("Device Size:   \t%zd bytes\n"
		      "Cookie:        \t0x%x (%d)\n",
		      desc->size, desc->cookie, desc->cookie);

		if (desc->iface_fns) {
			printf ("Device Function Table @ 0x%p\n", desc->iface_fns);
			switch (desc->family) {
			case Altera_ACEX1K:
			case Altera_CYC2:
#if defined(CONFIG_FPGA_ACEX1K)
				ACEX1K_info (desc);
#elif defined(CONFIG_FPGA_CYCLON2)
				CYC2_info (desc);
#else
				/* just in case */
				printf ("%s: No support for ACEX1K devices.\n",
						__FUNCTION__);
#endif
				break;
#if defined(CONFIG_FPGA_STRATIX_II)
			case Altera_StratixII:
				StratixII_info (desc);
				break;
#endif
				/* Add new family types here */
			default:
				/* we don't need a message here - we give one up above */
				break;
			}
		} else {
			printf ("No Device Function Table.\n");
		}

		ret_val = FPGA_SUCCESS;
	} else {
		printf ("%s: Invalid device descriptor\n", __FUNCTION__);
	}

	return ret_val;
}

/* ------------------------------------------------------------------------- */

static int altera_validate (Altera_desc * desc, const char *fn)
{
	int ret_val = false;

	if (desc) {
		if ((desc->family > min_altera_type) &&
			(desc->family < max_altera_type)) {
			if ((desc->iface > min_altera_iface_type) &&
				(desc->iface < max_altera_iface_type)) {
				if (desc->size) {
					ret_val = true;
				} else {
					printf ("%s: NULL part size\n", fn);
				}
			} else {
				printf ("%s: Invalid Interface type, %d\n",
					fn, desc->iface);
			}
		} else {
			printf ("%s: Invalid family type, %d\n", fn, desc->family);
		}
	} else {
		printf ("%s: NULL descriptor!\n", fn);
	}

	return ret_val;
}

/* ------------------------------------------------------------------------- */


text:
package cmd

import (
	"net"

	flag "github.com/spf13/pflag"

	"k8s.io/minikube/pkg/localkube"
	"k8s.io/minikube/pkg/minikube/constants"
	"k8s.io/minikube/pkg/util"
)

func NewLocalkubeServer() *localkube.LocalkubeServer {
	// net.ParseCIDR returns multiple values. Use the IPNet return value
	_, defaultServiceClusterIPRange, _ := net.ParseCIDR(util.DefaultServiceClusterIP + "/24")

	return &localkube.LocalkubeServer{
		Containerized:            false,
		DNSDomain:                util.DefaultDNSDomain,
		DNSIP:                    net.ParseIP(util.DefaultDNSIP),
		LocalkubeDirectory:       util.DefaultLocalkubeDirectory,
		ServiceClusterIPRange:    *defaultServiceClusterIPRange,
		APIServerAddress:         net.ParseIP("0.0.0.0"),
		APIServerPort:            constants.APIServerPort,
		APIServerInsecureAddress: net.ParseIP("127.0.0.1"),
		APIServerInsecurePort:    8080,
		APIServerName:            constants.APIServerName,
		ShouldGenerateCerts:      true,
		ShowVersion:              false,
		RuntimeConfig:            map[string]string{"api/all": "true"},
		ExtraConfig:              util.ExtraOptionSlice{},
	}
}

// AddFlags adds flags for a specific LocalkubeServer
func AddFlags(s *localkube.LocalkubeServer) {
	flag.BoolVar(&s.Containerized, "containerized", s.Containerized, "If kubelet should run in containerized mode")
	flag.BoolVar(&s.EnableDNS, "enable-dns", s.EnableDNS, "DEPRECATED: Please run kube-dns as a cluster addon")
	flag.StringVar(&s.DNSDomain, "dns-domain", s.DNSDomain, "The cluster dns domain")
	flag.IPVar(&s.DNSIP, "dns-ip", s.DNSIP, "The cluster dns IP")
	flag.StringVar(&s.LocalkubeDirectory, "localkube-directory", s.LocalkubeDirectory, "The directory localkube will store files in")
	flag.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, "The service-cluster-ip-range for the apiserver")
	flag.IPVar(&s.APIServerAddress, "apiserver-address", s.APIServerAddress, "The address the apiserver will listen securely on")
	flag.IntVar(&s.APIServerPort, "apiserver-port", s.APIServerPort, "The port the apiserver will listen securely on")
	flag.IPVar(&s.APIServerInsecureAddress, "apiserver-insecure-address", s.APIServerInsecureAddress, "The address the apiserver will listen insecurely on")
	flag.IntVar(&s.APIServerInsecurePort, "apiserver-insecure-port", s.APIServerInsecurePort, "The port the apiserver will listen insecurely on")
	flag.StringVar(&s.APIServerName, "apiserver-name", s.APIServerName, "The apiserver name which is used in the generated certificate for localkube/kubernetes.  This can be used if you want to make the API server available from outside the machine")

	flag.BoolVar(&s.ShouldGenerateCerts, "generate-certs", s.ShouldGenerateCerts, "If localkube should generate it's own certificates")
	flag.BoolVar(&s.ShowVersion, "show-version", s.ShowVersion, "If localkube should just print the version and exit.")
	flag.BoolVar(&s.ShowHostIP, "host-ip", s.ShowHostIP, "If localkube should just print the host IP and exit.")
	flag.Var(&s.RuntimeConfig, "runtime-config", "A set of key=value pairs that describe runtime configuration that may be passed to apiserver. apis/<groupVersion> key can be used to turn on/off specific api versions. apis/<groupVersion>/<resource> can be used to turn on/off specific resources. api/all and api/legacy are special keys to control all and legacy api versions respectively.")
	flag.IPVar(&s.NodeIP, "node-ip", s.NodeIP, "IP address of the node. If set, kubelet will use this IP address for the node.")
	flag.StringVar(&s.ContainerRuntime, "container-runtime", "", "The container runtime to be used")
	flag.StringVar(&s.NetworkPlugin, "network-plugin", "", "The name of the network plugin")
	flag.StringVar(&s.FeatureGates, "feature-gates", "", "A set of key=value pairs that describe feature gates for alpha/experimental features.")
	flag.Var(&s.ExtraConfig, "extra-config", "A set of key=value pairs that describe configuration that may be passed to different components. The key should be '.' separated, and the first part before the dot is the component to apply the configuration to.")

	// These two come from vendor/ packages that use flags. We should hide them
	flag.CommandLine.MarkHidden("google-json-key")
	flag.CommandLine.MarkHidden("log-flush-frequency")

	// Parse them
	flag.Parse()
}


text:
function byId(id) {
  return window.document.getElementById(id);
}

function mapForKeys(items, cb) {
  const obj = {};
  for (let i = 0; i < items.length; i += 1) {
    const item = items[i];
    obj[item] = cb(item);
  }
  return obj;
}

function byIds(ids) {
  return mapForKeys(ids, byId);
}

function byClass(className) {
  return window.document.getElementsByClassName(className);
}

function onLoad(fun) {
  const doc = window.document;
  const retry = () => { onLoad(fun); };
  if (/in/.test(doc.readyState)) {
    window.setTimeout(retry, 9, false);
  } else {
    fun();
  }
}

function noModifiers(e) {
  return !e.ctrkKey && !e.shiftKey && !e.altKey && !e.metaKey;
}

function onEvent(obj, evname, fun) {
  const handler = (e) => {
    const r = fun(e);
    if (r !== true) {
      e.preventDefault();
    }
  };
  if (obj instanceof NodeList) {
    [...obj].forEach((el) => {
      el.addEventListener(evname, handler, false);
    });
  } else {
    obj.addEventListener(evname, handler, false);
  }
}

function onKeyDown(handlermap) {
  onEvent(window, 'keydown', (e) => {
    const handler = handlermap[e.keyCode];
    if (typeof handler === 'function' && noModifiers(e)) {
      return handler(e);
    }
    return true;
  });
}

function removeCssClassPrefix(element, cssClassPrefix) {
  const cssClassesToRemove = [];
  element.classList.forEach((cssClass) => {
    if (cssClass.startsWith(cssClassPrefix)) {
      cssClassesToRemove.push(cssClass);
    }
  });
  cssClassesToRemove.forEach(
    (cssClass) => element.classList.remove(cssClass),
  );
}

function hide(element) {
  if (element) {
    // eslint-disable-next-line no-param-reassign
    element.style.display = 'none';
  }
}

function show(element, displayType) {
  if (element) {
    // eslint-disable-next-line no-param-reassign
    element.style.display = displayType || 'inline';
  }
}

function clearNode(node) {
  while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  }
}

function setChild(parent, child) {
  clearNode(parent);
  parent.appendChild(child);
}

exports.byClass = byClass;
exports.byId = byId;
exports.byIds = byIds;
exports.clearNode = clearNode;
exports.element = (el) => window.document.createElement(el);
exports.fragment = () => window.document.createDocumentFragment();
exports.getHashLocation = () => window.location.hash.substring(1);
exports.hide = hide;
exports.onEvent = onEvent;
exports.onKeyDown = onKeyDown;
exports.onLoad = onLoad;
exports.removeCssClassPrefix = removeCssClassPrefix;
exports.setChild = setChild;
exports.setHashLocation = (l) => { window.location = `#${l}`; };
exports.show = show;
exports.text = (s) => window.document.createTextNode(s);


text:
package com.citelic.game.entity.npc.impl.fightcaves;

import com.citelic.game.engine.task.EngineTask;
import com.citelic.game.engine.task.EngineTaskManager;
import com.citelic.game.entity.Animation;
import com.citelic.game.entity.Entity;
import com.citelic.game.entity.Graphics;
import com.citelic.game.entity.npc.combat.NPCCombatDefinitions;
import com.citelic.game.entity.player.content.controllers.impl.distractions.FightCaves;
import com.citelic.game.map.tile.Tile;

@SuppressWarnings("serial")
public class TzTok_Jad extends FightCavesNPC {

	private boolean spawnedMinions;
	private FightCaves controler;

	public TzTok_Jad(int id, Tile tile, FightCaves controler) {
		super(id, tile);
		this.controler = controler;
	}

	@Override
	public void processNPC() {
		super.processNPC();
		if (!spawnedMinions && getHitpoints() < getMaxHitpoints() / 2) {
			spawnedMinions = true;
			controler.spawnHealers();
		}
	}

	@Override
	public void sendDeath(Entity source) {
		final NPCCombatDefinitions defs = getCombatDefinitions();
		resetWalkSteps();
		getCombat().removeTarget();
		setNextAnimation(null);
		EngineTaskManager.schedule(new EngineTask() {
			int loop;

			@Override
			public void run() {
				if (loop == 0) {
					setNextAnimation(new Animation(defs.getDeathEmote()));
					setNextGraphics(new Graphics(2924 + getSize()));
				} else if (loop >= defs.getDeathDelay()) {
					reset();
					finish();
					controler.win();
					stop();
				}
				loop++;
			}
		}, 0, 1);
	}

}


text:
package net.i2p.router.peermanager;

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

import net.i2p.data.Hash;
import net.i2p.data.router.RouterInfo;
import net.i2p.data.TunnelId;
import net.i2p.data.i2np.DatabaseStoreMessage;
import net.i2p.data.i2np.DeliveryStatusMessage;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.router.JobImpl;
import net.i2p.router.MessageSelector;
import net.i2p.router.PeerSelectionCriteria;
import net.i2p.router.ReplyJob;
import net.i2p.router.RouterContext;
import net.i2p.router.TunnelInfo;
import net.i2p.util.Log;

/**
 * Grab some peers that we want to test and probe them briefly to get some
 * more accurate and up to date performance data.  This delegates the peer
 * selection to the peer manager and tests the peer by sending it a useless
 * database store message
 *
 * TODO - What's the point? Disable this? See also notes in PeerManager.selectPeers()
 */
public class PeerTestJob extends JobImpl {
    private final Log _log;
    private PeerManager _manager;
    private boolean _keepTesting;
    private static final long DEFAULT_PEER_TEST_DELAY = 5*60*1000;
    /** Creates a new instance of PeerTestJob */
    public PeerTestJob(RouterContext context) {
        super(context);
        _log = context.logManager().getLog(PeerTestJob.class);
        _keepTesting = false;
        getContext().statManager().createRateStat("peer.testOK", "How long a successful test takes", "Peers", new long[] { 60*1000, 10*60*1000 });
        getContext().statManager().createRateStat("peer.testTooSlow", "How long a too-slow (yet successful) test takes", "Peers", new long[] { 60*1000, 10*60*1000 });
        getContext().statManager().createRateStat("peer.testTimeout", "How often a test times out without a reply", "Peers", new long[] { 60*1000, 10*60*1000 });
    }

    /** how long should we wait before firing off new tests?  */
    private long getPeerTestDelay() { return DEFAULT_PEER_TEST_DELAY; }
    /** how long to give each peer before marking them as unresponsive? */
    private int getTestTimeout() { return 30*1000; }
    /** number of peers to test each round */
    private int getTestConcurrency() { return 1; }

    // FIXME Exporting non-public type through public API FIXME
    public synchronized void startTesting(PeerManager manager) {
        _manager = manager;
        _keepTesting = true;
        this.getTiming().setStartAfter(getContext().clock().now() + DEFAULT_PEER_TEST_DELAY);
        getContext().jobQueue().addJob(this);
        if (_log.shouldLog(Log.INFO))
            _log.info("Start testing peers");
    }

    public synchronized void stopTesting() {
        _keepTesting = false;
        if (_log.shouldLog(Log.INFO))
            _log.info("Stop testing peers");
    }

    public String getName() { return "Peer test start"; }

    public void runJob() {
        if (!_keepTesting) return;
        Set<RouterInfo> peers = selectPeersToTest();
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Testing " + peers.size() + " peers");

        for (RouterInfo peer : peers) {
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Testing peer " + peer.getIdentity().getHash().toBase64());
            testPeer(peer);
        }
        requeue(getPeerTestDelay());
    }

    /**
     * Retrieve a group of 0 or more peers that we want to test.
     *
     * @return set of RouterInfo structures
     */
    private Set<RouterInfo> selectPeersToTest() {
        PeerSelectionCriteria criteria = new PeerSelectionCriteria();
        criteria.setMinimumRequired(getTestConcurrency());
        criteria.setMaximumRequired(getTestConcurrency());
        criteria.setPurpose(PeerSelectionCriteria.PURPOSE_TEST);
        List<Hash> peerHashes = _manager.selectPeers(criteria);

        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Peer selection found " + peerHashes.size() + " peers");

        Set<RouterInfo> peers = new HashSet<RouterInfo>(peerHashes.size());
        for (Hash peer : peerHashes) {
            RouterInfo peerInfo = getContext().netDb().lookupRouterInfoLocally(peer);
            if (peerInfo != null) {
                peers.add(peerInfo);
            } else {
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Test peer " + peer.toBase64() + " had no local routerInfo?");
            }
        }
        return peers;
    }

    /**
     * Fire off the necessary jobs and messages to test the given peer
     *
     */
    private void testPeer(RouterInfo peer) {
        TunnelInfo inTunnel = getInboundTunnelId();
        if (inTunnel == null) {
            _log.warn("No tunnels to get peer test replies through!  wtf!");
            return;
        }
        TunnelId inTunnelId = inTunnel.getReceiveTunnelId(0);

        RouterInfo inGateway = getContext().netDb().lookupRouterInfoLocally(inTunnel.getPeer(0));
        if (inGateway == null) {
            if (_log.shouldLog(Log.WARN))
                _log.warn("We can't find the gateway to our inbound tunnel?! wtf");
            return;
        }

        int timeoutMs = getTestTimeout();
        long expiration = getContext().clock().now() + timeoutMs;

        long nonce = getContext().random().nextLong(I2NPMessage.MAX_ID_VALUE);
        DatabaseStoreMessage msg = buildMessage(peer, inTunnelId, inGateway.getIdentity().getHash(), nonce, expiration);

        TunnelInfo outTunnel = getOutboundTunnelId();
        if (outTunnel == null) {
            _log.warn("No tunnels to send search out through!  wtf!");
            return;
        }

        TunnelId outTunnelId = outTunnel.getSendTunnelId(0);

        if (_log.shouldLog(Log.DEBUG))
            _log.debug(getJobId() + ": Sending peer test to " + peer.getIdentity().getHash().toBase64()
                       + " out " + outTunnel + " w/ replies through " + inTunnel);

        ReplySelector sel = new ReplySelector(peer.getIdentity().getHash(), nonce, expiration);
        PeerReplyFoundJob reply = new PeerReplyFoundJob(getContext(), peer, inTunnel, outTunnel);
        PeerReplyTimeoutJob timeoutJob = new PeerReplyTimeoutJob(getContext(), peer, inTunnel, outTunnel, sel);

        getContext().messageRegistry().registerPending(sel, reply, timeoutJob);
        getContext().tunnelDispatcher().dispatchOutbound(msg, outTunnelId, null, peer.getIdentity().getHash());
    }

    /**
     * what tunnel will we send the test out through?
     *
     * @return tunnel id (or null if none are found)
     */
    private TunnelInfo getOutboundTunnelId() {
        return getContext().tunnelManager().selectOutboundTunnel();
    }

    /**
     * what tunnel will we get replies through?
     *
     * @return tunnel id (or null if none are found)
     */
    private TunnelInfo getInboundTunnelId() {
        return getContext().tunnelManager().selectInboundTunnel();
    }

    /**
     * Build a message to test the peer with
     */
    private DatabaseStoreMessage buildMessage(RouterInfo peer, TunnelId replyTunnel, Hash replyGateway, long nonce, long expiration) {
        DatabaseStoreMessage msg = new DatabaseStoreMessage(getContext());
        msg.setEntry(peer);
        msg.setReplyGateway(replyGateway);
        msg.setReplyTunnel(replyTunnel);
        msg.setReplyToken(nonce);
        msg.setMessageExpiration(expiration);
        return msg;
    }

    /**
     * Simple selector looking for a dbStore of the peer specified
     *
     */
    private class ReplySelector implements MessageSelector {
        private long _expiration;
        private long _nonce;
        private Hash _peer;
        private boolean _matchFound;
        public ReplySelector(Hash peer, long nonce, long expiration) {
            _nonce = nonce;
            _expiration = expiration;
            _peer = peer;
            _matchFound = false;
        }
        public boolean continueMatching() { return false; }
        public long getExpiration() { return _expiration; }
        public boolean isMatch(I2NPMessage message) {
            if (message instanceof DeliveryStatusMessage) {
                DeliveryStatusMessage msg = (DeliveryStatusMessage)message;
                if (_nonce == msg.getMessageId()) {
                    long timeLeft = _expiration - getContext().clock().now();
                    if (timeLeft < 0) {
                        if (_log.shouldLog(Log.WARN))
                            _log.warn("Took too long to get a reply from peer " + _peer.toBase64()
                                      + ": " + (0-timeLeft) + "ms too slow");
                        getContext().statManager().addRateData("peer.testTooSlow", 0-timeLeft);
                    } else {
                        getContext().statManager().addRateData("peer.testOK", getTestTimeout() - timeLeft);
                    }
                    _matchFound = true;
                    return true;
                }
            }
            return false;
        }
        public boolean matchFound() { return _matchFound; }
        @Override
        public String toString() {
            StringBuilder buf = new StringBuilder(64);
            buf.append("Test peer ").append(_peer.toBase64().substring(0,4));
            buf.append(" with nonce ").append(_nonce);
            return buf.toString();
        }
    }

    /**
     * Called when the peer's response is found
     */
    private class PeerReplyFoundJob extends JobImpl implements ReplyJob {
        private RouterInfo _peer;
        private long _testBegin;
        private TunnelInfo _replyTunnel;
        private TunnelInfo _sendTunnel;
        public PeerReplyFoundJob(RouterContext context, RouterInfo peer, TunnelInfo replyTunnel, TunnelInfo sendTunnel) {
            super(context);
            _peer = peer;
            _replyTunnel = replyTunnel;
            _sendTunnel = sendTunnel;
            _testBegin = context.clock().now();
        }
        public String getName() { return "Peer test successful"; }
        public void runJob() {
            long responseTime = getContext().clock().now() - _testBegin;

            if (_log.shouldLog(Log.DEBUG))
                _log.debug("successful peer test after " + responseTime + " for "
                           + _peer.getIdentity().getHash().toBase64() + " using outbound tunnel "
                           + _sendTunnel + " and inbound tunnel "
                           + _replyTunnel);
            getContext().profileManager().dbLookupSuccessful(_peer.getIdentity().getHash(), responseTime);
            // we know the tunnels are working
            _sendTunnel.testSuccessful((int)responseTime);
            _replyTunnel.testSuccessful((int)responseTime);
        }

        public void setMessage(I2NPMessage message) {
            // noop
        }

    }
    /**
     * Called when the peer's response times out
     */
    private class PeerReplyTimeoutJob extends JobImpl {
        private RouterInfo _peer;
        private TunnelInfo _replyTunnel;
        private TunnelInfo _sendTunnel;
        private ReplySelector _selector;
        public PeerReplyTimeoutJob(RouterContext context, RouterInfo peer, TunnelInfo replyTunnel, TunnelInfo sendTunnel, ReplySelector sel) {
            super(context);
            _peer = peer;
            _replyTunnel = replyTunnel;
            _sendTunnel = sendTunnel;
            _selector = sel;
        }
        public String getName() { return "Peer test failed"; }
        private boolean getShouldFailPeer() { return true; }
        public void runJob() {
            if (_selector.matchFound())
                return;

            if (getShouldFailPeer())
                getContext().profileManager().dbLookupFailed(_peer.getIdentity().getHash());

            if (_log.shouldLog(Log.DEBUG))
                _log.debug("failed peer test for "
                           + _peer.getIdentity().getHash().toBase64() + " using outbound tunnel "
                           + _sendTunnel + " and inbound tunnel "
                           + _replyTunnel);

            // don't fail the tunnels, as the peer might just plain be down, or
            // otherwise overloaded
            getContext().statManager().addRateData("peer.testTimeout", 1);
        }
    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('seedsource', '0011_alter_shareurl_configuration'),
    ]

    operations = [
        migrations.AlterField(
            model_name='region',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='runconfiguration',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='seedzone',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='shareurl',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='transferlimit',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
        migrations.AlterField(
            model_name='zonesource',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
    ]


text:
package mariculture.magic.enchantments;

import mariculture.api.core.MaricultureHandlers;
import mariculture.core.config.Enchantments.Jewelry;
import mariculture.core.helpers.EnchantHelper;
import mariculture.magic.Magic;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.event.entity.living.LivingDeathEvent;

public class EnchantmentResurrection extends EnchantmentJewelry {
    public static final String spawnX = "ResurrectionSpawnX";
    public static final String spawnY = "ResurrectionSpawnY";
    public static final String spawnZ = "ResurrectionSpawnZ";
    public static final String armor = "ResurrectionArmorList";
    public static final String inventory = "ResurrectionInventoryList";
    public static final String resistTime = "ResurrectionResistTime";

    public EnchantmentResurrection(int i, int weight, EnumEnchantmentType type) {
        super(i, weight, type);
        setName("resurrection");
        minLevel = 50;
        maxLevel = 55;
    }

    @Override
    public int getMaxLevel() {
        return 3;
    }

    public static void activate(LivingDeathEvent event) {
        if (event.entity instanceof EntityPlayer) {
            EntityPlayer player = (EntityPlayer) event.entity;

            if (EnchantHelper.hasEnchantment(Magic.resurrection, player) && !player.worldObj.isRemote) {
                if (!player.getEntityData().hasKey(EntityPlayer.PERSISTED_NBT_TAG)) {
                    player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, new NBTTagCompound());
                }

                if (!event.source.isFireDamage() && !event.source.canHarmInCreative() && EnchantHelper.getEnchantStrength(Magic.resurrection, player) > 1) {
                    player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setInteger(spawnX, (int) player.posX);
                    player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setInteger(spawnY, (int) player.posY);
                    player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setInteger(spawnZ, (int) player.posZ);
                }

                if (EnchantHelper.getEnchantStrength(Magic.resurrection, player) > 2) {
                    int modifier = EnchantHelper.getEnchantStrength(Magic.resurrection, player);
                    player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setInteger(resistTime, 50 * modifier);
                }

                /* Save Main Inventory */
                ItemStack[] inv = player.inventory.mainInventory;
                NBTTagList nbttaglist = new NBTTagList();
                for (int i = 0; i < inv.length; i++)
                    if (inv[i] != null) {
                        final NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                        nbttagcompound1.setByte("Slot", (byte) i);
                        inv[i].writeToNBT(nbttagcompound1);
                        nbttaglist.appendTag(nbttagcompound1);
                    }

                player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setTag(inventory, nbttaglist);

                // Save Armor
                ItemStack[] arm = player.inventory.armorInventory;
                NBTTagList armorList = new NBTTagList();
                for (int i = 0; i < arm.length; i++)
                    if (arm[i] != null) {
                        final NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                        nbttagcompound1.setByte("Slot", (byte) i);
                        arm[i].writeToNBT(nbttagcompound1);
                        armorList.appendTag(nbttagcompound1);
                    }

                player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).setTag(armor, armorList);

                event.setCanceled(true);
            } else if (Jewelry.DROP_JEWELRY && player.worldObj.getGameRules().getGameRuleBooleanValue("keepInventory") == false) {
                MaricultureHandlers.mirror.dropItems(player, player.worldObj, player.posX, player.posY, player.posZ);
            }
        }
    }
}


text:
layout: page
title: Navs
---

Basic

    With a basic nav you will probably want to apply a custom width to the .c-nav
    element, otherwise it will appear with 100% width.

MY APP

 Create New

 Home

 About

 News

 Help

<ul class="c-nav">
<li class="c-nav__content">MY APP</li>
<li class="c-nav__item c-nav__item--success c-nav__item--active">Create New</li>
<li class="c-nav__item">Home</li>
<li class="c-nav__item c-nav__item--brand">About</li>
<li class="c-nav__item c-nav__item--info">News</li>
<li class="c-nav__item c-nav__item--error">Help</li>
</ul>

Inline nav (with right aligned item)

 Home

 News

 Contact

<ul class="c-nav c-nav--inline">
  <li class="c-nav__item">Home</li>
  <li class="c-nav__item">News</li>
  <li class="c-nav__item c-nav__item--right">Contact</li>
</ul>

Absolute positions

.c-nav--top or .c-nav--bottom

    Fix the nav to the top or bottom of the parent element, best used with .c-nav--inline.

.c-nav--left or .c-nav--right

    Fix the nav to the left or right of the parent element, you must apply a width otherwise it will consume the entire
    container!

Fixed position

.c-nav--fixed

    Fix the nav in position so that it doesn't move on scroll.

Shadows

    Add the standard elevation modifiers to give the nav the appearance that it is hovering above the page.

         Home
         News
         Contact

Images

    Navs support images really well too. Just wrap your .o-image inside a
    .c-nav__content element.

         Home
         News
         Contact

Light variation

 Home

 News

 Contact

<ul class="c-nav c-nav--light">
  <li class="c-nav__item">Home</li>
  <li class="c-nav__item">News</li>
  <li class="c-nav__item c-nav__item--right">Contact</li>
</ul>


text:
Script
=======================

Access the pipelines state using `state`

e.g.

.. code-block:: python

    unknown_analyses = state.unknowns

for convenience the unknowns are exposed directly via `unknowns`

.. code-block:: python

    #the follow are equivalent
    ans = state.unknowns
    ans = unknowns

Available attributes for analyses

.. code-block::

    # the first analysis in the list
    analysis = unknowns[0]

    # a dictionary of `Isotope` objects
    isotopes = analysis.isotopes

    age = analysis.age

    # age as a `ufloat` object
    uage = analysis.uage

    from uncertainties import nominal_value, std_dev
    age = nominal_value(uage)
    age_err = std_dev(uage)

    # or
    age = analysis.age
    age_w_j_err = analysis.age_err

    # see ArArAge for comprehensive view of the Analysis object

Analysis Attributes
----------------------------
========================= ====== =================
Attribute                 Type   Description
========================= ====== =================
kca                       ufloat  K/Ca
cak                       ufloat  Ca/K
kcl                       ufloat  K/Cl
clk                       ufloat  Cl/K
radiogenic_yield          ufloat  %40Ar*
rad40                     ufloat  40Ar*
total40                   ufloat
k39                       ufloat
uF                        ufloat
F                         float
F_err                     float
F_err_wo_irrad            float
uage                      ufloat
uage_w_j_err              ufloat
uage_w_position_err       ufloat
age                       float
age_err                   float
age_err_wo_j              float
age_err_wo_irrad          float
age_err_wo_j_irrad        float
ar39decayfactor           float
ar37decayfactor           float
isotopes                  dict   Dictionary of isotopes
isochron3940              ufloat
isochron3640              ufloat
lambda_k                  ufloat
irradiation_label
decay_days
moles_k39
========================= ====== =================

Analysis Methods

====================================== ================== ============= =================
Method                                 Arguments          Return        Description
====================================== ================== ============= =================
get_interference_corrected_value       str                ufloat
get_corrected_ratio                    str, str           ufloat
get_value                              str                ufloat
====================================== ================== ============= =================

.. code-block:: python

    get_interference_corrected_value('Ar40')
    get_corrected_ratio('Ar38', 'Ar36')  # returns Ar38/Ar36 ratio
    get_value('age')  # helper function for getting commonly accessed values

Isotope Attributes
--------------------------
========================= ========= =================
Attribute                 Type      Description
========================= ========= =================
name                      str       Name of the isotope e.g. Ar40
detector                  str       Name of detector used to measure isotope e.g. H1
n                         int       Total number of data points collected. e.g. len(xs)
fn                        int       Total number of data points collected. e.g. len(xs)
offset_xs                 array
xs                        array
ys                        array
fit                       str
value                     float
error                     float
uvalue                    ufloat
baseline                  Isotope
blank                     Isotope
========================= ========= =================

Isotope Methods
------------------------
====================================== ============= =================
Method                                 Return        Description
====================================== ============= =================
get_baseline_corrected_value           ufloat
get_ic_decay_corrected_value           ufloat
get_decay_corrected_value              ufloat
get_interference_corrected_value       ufloat
get_disc_corrected_value               ufloat
get_ic_corrected_value                 ufloat
get_non_detector_corrected_value       ufloat
====================================== ============= =================

Plotting Examples
---------------------------------
Plot with error bars
++++++++++++++++++++++++
.. code-block:: python

    import matplotlib.pyplot as plt
    from uncertainties import nominal_value, std_dev

    def main():

        ns = [a.get_value('Ar40/Ar38') for a in unknowns]
        ds = [a.get_value('Ar40/Ar36') for a in unknowns]

        xs = [nominal_value(di) for di in ds]
        ys = [nominal_value(ni) for ni in ns]

        xerrs = [std_dev(di) for di in ds]
        yerrs = [std_dev(ni) for ni in ns]

        plt.ylabel('Ar40/Ar36')
        plt.xlabel('Ar40/Ar38')

        plt.errorbar(xs, ys, xerr=xerrs, yerr=yerrs, fmt='bo')

        plt.show()

Simple scatter plot
++++++++++++++++++++++++
.. code-block:: python

    import matplotlib.pyplot as plt
    from uncertainties import nominal_value, std_dev

    def main():

        ns = [a.get_value('Ar40/Ar38') for a in unknowns]
        ds = [a.get_value('Ar40/Ar36') for a in unknowns]

        xs = [nominal_value(di) for di in ds]
        ys = [nominal_value(ni) for ni in ns]

        plt.ylabel('Ar40/Ar36')
        plt.xlabel('Ar40/Ar38')

        plt.plot(xs, ys, 'bo')

        plt.show()


text:
using CheckinSuite.Exceptions;
using CheckinSuite.JsonObjects;
using CheckinSuite.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CheckinSuite.Controllers
{
    public class FirstTimeCheckinController : Controller
    {

        // Pages
        public ActionResult Setup()
        {
            return View();
        }

        public ActionResult Index()
        {
            ViewBag.AdultAge = ConfigurationManager.AppSettings["AdultAge"];
            return View();
        }

        public ActionResult EditHousehold(int id)
        {
            ViewBag.householdId = id;
            return View();
        }

        // Ajax pages
        public ActionResult CreatePerson(HouseholdModel data)
        {
            JsonResponse response = new JsonResponse();

            if (data.Children != null && data.Children.Count == 1)
            {
                ChildHouseholdMember child = data.Children[0];
                child.HouseholdPositionId = 2; // minor child
                child.HouseholdId = MinistryPlatform.CreateHouseholdWithPhone(child, data.HouseholdPhone);
                MinistryPlatform.CreatePerson(child);
                MinistryPlatform.CreateGroupParticipant(child);
                response.Add("householdId", child.HouseholdId);
            }
            else if (data.Adults != null && data.Adults.Count == 1)
            {
                HouseholdMember adult = data.Adults[0];
                adult.HouseholdPositionId = 1; // head of household
                adult.HouseholdId = MinistryPlatform.CreateHouseholdWithPhone(adult, data.HouseholdPhone);
                MinistryPlatform.CreatePerson(adult);
                response.Add("householdId", adult.HouseholdId);
            }
            else
            {
                response.isSuccess = false;
                response.errorText = "multiple people passed in";
            }

            return Content(response.serialize(), "application/json");
        }

        public ActionResult Submit(HouseholdModel data)
        {
            JsonResponse response = new JsonResponse();

            if (data.Adults != null)
            {
                foreach (HouseholdMember adult in data.Adults)
                {
                    if (adult.HasContact())
                    {
                        response.isSuccess = false;
                        response.errorText = adult.ContactId + "|Is already in the system";
                        response.Add("contactId", adult.ContactId);
                        response.Add("firstName", adult.FirstName);
                        response.Add("lastName", adult.LastName);
                        response.Add("householdId", data.HouseholdId);
                    }
                    else
                    {
                        adult.HouseholdId = data.HouseholdId; // sets the adult's householdId to the current household
                        MinistryPlatform.CreatePerson(adult);

                    }
                }
            }

            if (data.Children != null)
            {
                foreach (ChildHouseholdMember child in data.Children)
                {
                    if (child.HasContact()) // Does child already Exist?
                    {
                        if (!child.ParticipantId.HasValue)
                        {
                            child.ParticipantId = MinistryPlatform.CreateParticipant(child);
                            MinistryPlatform.UpdateContact(child);
                        }

                        if (child.Relation == ChildHouseholdMember.RelationTypes.Child)
                        {
                            MinistryPlatform.CreateGroupParticipant(child);

                            string householdName = MinistryPlatform.GetHouseholdName(data.HouseholdId);

                            MinistryPlatform.CreateDataNote(child.ContactId.Value, "Existing Contact Added to Household", "A Contact_Household record was created to pair this contact to " + householdName + " [#" + data.HouseholdId + "] household. If this is correct reassign this contact to the new household, otherwise change " + householdName + "Other Household relationship to 'Guest' or 'Grandchild'.", "", ConfigurationManager.AppSettings["FirstTimeCheckinUserID"]);
                            MinistryPlatform.CreateShowsInCheckinWithEndDate(child, data.HouseholdId);
                        }
                        else if (child.Relation == ChildHouseholdMember.RelationTypes.Grandchild || child.Relation == ChildHouseholdMember.RelationTypes.Guest)
                        {
                            try
                            {
                                MinistryPlatform.GetGroupParticipant(child.ParticipantId.Value, child.Grade); // check if group participants already exsit
                            }
                            catch (StoredProcReturnedEmptyException)
                            {
                                // if they dont. create one
                                MinistryPlatform.CreateGroupParticipant(child);
                            }

                            if (child.IsRegular)
                            {
                                MinistryPlatform.CreateShowsInCheckin(child, data.HouseholdId);
                            }
                            else
                            {
                                MinistryPlatform.CreateShowsInCheckinWithEndDate(child, data.HouseholdId);
                            }
                            MinistryPlatform.CreateDataNote(child.ContactId.Value, child.Relation.ToString() + " linked to household", "Informational", "", ConfigurationManager.AppSettings["FirstTimeCheckinUserID"]);
                        }
                    }
                    else
                    {
                        if (child.Relation == ChildHouseholdMember.RelationTypes.Child)
                        {
                            child.HouseholdId = data.HouseholdId;
                            MinistryPlatform.CreatePerson(child);
                            MinistryPlatform.CreateGroupParticipant(child);
                        }
                        else if (child.Relation == ChildHouseholdMember.RelationTypes.Grandchild || child.Relation == ChildHouseholdMember.RelationTypes.Guest)
                        {
                            // In this situation, we are creating a new household for this child. In the household we want them to be a child, not a grandchild/guest like it is now
                            child.HouseholdPositionId = 2;

                            child.HouseholdId = MinistryPlatform.CreateHousehold(child);
                            MinistryPlatform.CreatePerson(child);
                            MinistryPlatform.CreateGroupParticipant(child);

                            // pair the contact to data's household, not the one we just created
                            if (child.IsRegular)
                            {
                                MinistryPlatform.CreateShowsInCheckin(child, data.HouseholdId);
                            }
                            else
                            {
                                MinistryPlatform.CreateShowsInCheckinWithEndDate(child, data.HouseholdId);
                            }
                        }
                    }
                }
            }

            return Content(response.serialize(), "application/json");
        }

        public ActionResult CreateDataNote(DataNoteModel data)
        {
            if (data.UserId == null)
            {
                data.UserId = ConfigurationManager.AppSettings["FirstTimeCheckinUserID"];
            }

            MinistryPlatform.CreateDataNote(data);

            return Content(new JsonResponse().serialize(), "application/json");
        }

        public ActionResult GetHouseholdContacts()
        {
            JsonResponse response = new JsonResponse();

            int householdId = Convert.ToInt32(Request.Form["householdId"]);

            DataTable householdsContacts = MinistryPlatform.GetHouseholdContacts(householdId);

            response.Add("householdMembers", JsonParser.Table(householdsContacts));

            return Content(response.serialize(), "application/json");
        }

        public ActionResult FindContact(HouseholdMember data)
        {
            JsonResponse response = new JsonResponse();

            if (data.HasContact())
            {
                DataRow contactData = MinistryPlatform.GetContact(data).Rows[0];

                if (Convert.IsDBNull(contactData["Participant_Record"]))
                {
                   data.ParticipantId = MinistryPlatform.CreateParticipant(data);
                }
                else
                {
                    data.ParticipantId = (int)contactData["Participant_Record"];
                }

                if (Convert.IsDBNull(contactData["Household_ID"]))
                {
                   data.HouseholdId = MinistryPlatform.CreateHousehold(data);
                }
                else
                {
                    data.HouseholdId = (int)contactData["Household_ID"];
                }

                if (Convert.IsDBNull(contactData["Participant_Record"]) || Convert.IsDBNull(contactData["Household_ID"]))
                {
                    MinistryPlatform.UpdateContact(data);
                }

                response.Add("householdId", data.HouseholdId);

            }
            else
            {
                response.isSuccess = false;
                response.errorText = "No Contact Found";
            }

            return Content(response.serialize(), "application/json");
        }

        private int calculateAge(string dateOfBirth)
        {
            DateTime person = Convert.ToDateTime(dateOfBirth);
            DateTime now = DateTime.Now;
            return now.Year - person.Year;
        }

        public ActionResult GetGradeGroups()
        {
            JsonResponse response = new JsonResponse();
            DataTable table = MinistryPlatform.GetGradeGroups();

            List<LightboxSelectItem> groups = new List<LightboxSelectItem>();

            LightboxSelectItem currentSection = new LightboxSelectItem(); // create an empty object
            foreach (DataRow row in table.Rows)
            {
                if (currentSection.value != row["Parent_Group_ID"].ToString())
                {
                    currentSection = new LightboxSelectItem();
                    currentSection.value = row["Parent_Group_ID"].ToString();
                    currentSection.title = row["Parent_Group_Name"].ToString();

                    groups.Add(currentSection);
                }

                LightboxSelectItem addingItem = new LightboxSelectItem();
                addingItem.title = row["Group_Name"].ToString();
                addingItem.value = row["Group_ID"].ToString();
                currentSection.items.Add(addingItem);
            }

            response.Add("groups", groups);

            return Content(response.serialize(), "application/json");
        }

    }
}


text:
import React from 'react'

export const HomeView = () => (

About this project

      The main focus of this project is the mixed 2D/3D rendering of Github language and repo activity.

      For this project, the activity of a repo is defined as the number of stars is has.
      The activity of a language is defined as the sum of the 30 most active repos that were created after a fixed date.

)

export default HomeView


text:
package manage

import (
	"net/url"
	"strings"

	"gopkg.in/oauth2.v3/errors"
)

type (
	// ValidateURIHandler validates that redirectURI is contained in baseURI
	ValidateURIHandler func(baseURI, redirectURI string) (err error)
)

// DefaultValidateURI validates that redirectURI is contained in baseURI
func DefaultValidateURI(baseURI string, redirectURI string) (err error) {
	base, err := url.Parse(baseURI)
	if err != nil {
		return
	}
	redirect, err := url.Parse(redirectURI)
	if err != nil {
		return
	}
	if !strings.HasSuffix(redirect.Host, base.Host) {
		err = errors.ErrInvalidRedirectURI
	}
	return
}


text:
<?php declare(strict_types=1);

namespace PAF\Common\Localization;

use Nette\Localization\ITranslator;

class TranslatorUtils
{
    /**
     * Using provided `$translator`, translates each item in `$values`
     *
     * @param string[] $values
     * @param ITranslator $translator
     * @return string[]
     */
    public static function mapTranslate(array $values, ITranslator $translator): array
    {
        $result = [];

        foreach ($values as $key => $value) {
            $result[$key] = $translator->translate($value);
        }

        return $result;
    }
}


text:
import * as React from "react";
import {Bubble} from "react-chartjs-2";
import Point from "../types/Point";
import {ChartOptions} from "chartjs";

interface InterpolationCurveProps {
    points: Point[],
    curvePoints: { [propname: string]: Point[] }
}

export default class InterpolationCurve extends React.Component<InterpolationCurveProps, {}> {

    render() {

        const colors = [
            "red", "green", "blue"
        ];

        const data = {
            labels: ['Interpolation'],
            datasets: Object.keys(this.props.curvePoints).map(key => {
                return {
                    label: key,
                    fill: true,
                    backgroundColor: 'rgba(75,192,192,0.4)',
                    borderColor: 'rgba(75,192,192,1)',
                    borderCapStyle: 'butt',
                    borderDash: [],
                    borderDashOffset: 0.0,
                    borderJoinStyle: 'miter',
                    pointBorderColor: 'rgba(75,192,192,1)',
                    pointBackgroundColor: '#fff',
                    pointBorderWidth: 1,
                    pointHoverRadius: 5,
                    pointHoverBackgroundColor: 'rgba(75,192,192,1)',
                    pointHoverBorderColor: 'rgba(220,220,220,1)',
                    pointHoverBorderWidth: 2,
                    pointRadius: 1,
                    pointHitRadius: 10,
                    data: this.props.curvePoints[key],
                    type: "line",
                    lineTension: 0.3
                }
            })
        };

        return <div style={{width: 800, height: 600}}>
            <Bubble data={data} />
        </div>;
    }

}


text:
========
Usage
========

To use pyeasyga in a project:

Simple
------

    1. Import the module ::

        from pyeasyga import pyeasyga

    2. Setup your data e.g. ::

        data = [('pear', 50), ('apple', 35), ('banana', 40)]

    3. Initialise the GeneticAlgorithm class with the only required
       parameter: ``data`` ::

        ga = pyeasyga.GeneticAlgorithm(data)

    4. Define a fitness function for the Genetic Algorithm. The function should
       take two parameters: a candidate soultion (an individual in GA speak),
       and the data that is used to help determine the individual's fitness ::

        def fitness (individual, data):
            fitness = 0
            if individual.count(1) == 2:
                for (selected, (fruit, profit)) in zip(individual, data):
                    if selected:
                        fitness += profit
            return fitness

    5. Set the Genetic Algorithm's ``fitness_function`` attribute to your
       defined fitness function ::

        ga.fitness_function = fitness

    6. Run the Genetic Algorithm ::

        ga.run()

    7. Print the best solution ::

        print ga.best_individual()

Advanced
--------

    1. Import the module ::

        from pyeasyga import pyeasyga

    2. Setup your data e.g. ::

        data = [('pear', 50), ('apple', 35), ('banana', 40)]

    3. Initialise the GeneticAlgorithm class with the required ``data``
       parameter, and all or some of the optional parameters ::

        ga = pyeasyga.GeneticAlgorithm(data,
                                       population_size=10,
                                       generations=20,
                                       crossover_probability=0.8,
                                       mutation_probability=0.05,
                                       elitism=True,
                                       maximise_fitness=True,
                                       verbose=False)

       Or ::

            ga = pyeasyga.GeneticAlgorithm(data, 10, 20, 0.8, 0.05, True, True)

       Or, just initialise the GeneticAlgorithm class with only the required
       ``data`` parameter, if you are content with the default parameters ::

            ga = pyeasyga.GeneticAlgorithm(data)

    4. Optionally, define a function to create a representation of a candidate
       solution (an individual in GA speak). This function should take in the
       data defined in step 1. as a parameter. ::

        def create_individual(data):
            return [random.randint(0, 1) for _ in xrange(len(data))]

    5. Set the Genetic Algorithm's ``create_individual`` attribute to your
       defined function ::

        ga.create_individual = create_individual

    6. Optionally, define and set functions for the Genetic Algorithm's genetic
       operators (i.e. crossover, mutate, selection) ::

        # For the crossover function, supply two individuals (i.e. candidate
        # solution representations) as parameters,
        def crossover(parent_1, parent_2):
            crossover_index = random.randrange(1, len(parent_1))
            child_1 = parent_1[:index] + parent_2[index:]
            child_2 = parent_2[:index] + parent_1[index:]
            return child_1, child_2

        # and set the Genetic Algorithm's ``crossover_function`` attribute to
        # your defined function
        ga.crossover_function = crossover

        # For the mutate function, supply one individual (i.e. a candidate
        # solution representation) as a parameter,
        def mutate(individual):
            mutate_index = random.randrange(len(individual))
            if individual[mutate_index] == 0:
                individual[mutate_index] = 1
            else:
                individual[mutate_index] = 0

        # and set the Genetic Algorithm's ``mutate_function`` attribute to
        # your defined function
        ga.mutate_function = mutate

        # For the selection function, supply a ``population`` parameter
        def selection(population):
            return random.choice(population)

        # and set the Genetic Algorithm's ``selection_function`` attribute to
        # your defined function
        ga.selection_function = selection

    7. Define a fitness function for the Genetic Algorithm. The function should
       take two parameters: a candidate solution representation (an individual
       in GA speak), and the data that is used to help determine the
       individual's fitness ::

        def fitness (individual, data):
            fitness = 0
            if individual.count(1) == 2:
                for (selected, (fruit, profit)) in zip(individual, data):
                    if selected:
                        fitness += profit
            return fitness

    8. Set the Genetic Algorithm's ``fitness_function`` attribute to your
       defined fitness function ::

        ga.fitness_function = fitness

    9. Run the Genetic Algorithm ::

        ga.run()

    #. Print the best solution::

        print ga.best_individual()

    #. You can also examine all the individuals in the last generation::

        for individual in ga.last_generation():
            print individual

Example of Simple Usage
-----------------------

This simple example uses the default ``pyeasyga.GeneticAlgorithm`` parameters.

The problem is to select only two items from a list (the supplied data) while
maximising the cost of the selected items. *(Solution: Selecting the pear and
apple gives the highest possible cost of 90.)* ::

    >>> from pyeasyga.pyeasyga import GeneticAlgorithm
    >>>
    >>> data = [('pear', 50), ('apple', 35), ('banana', 40)]
    >>> ga = GeneticAlgorithm(data)
    >>>
    >>> def fitness (individual, data):
    >>>     fitness = 0
    >>>     if individual.count(1) == 2:
    >>>         for (selected, (fruit, profit)) in zip(individual, data):
    >>>             if selected:
    >>>                 fitness += profit
    >>>     return fitness
    >>>
    >>> ga.fitness_function = fitness
    >>> ga.run()
    >>> print ga.best_individual()

Example of Advanced Usage
-------------------------

This example uses both default and optional ``pyeasyga.GeneticAlgorithm``
parameters.

The problem is to select only two items from a list (the supplied data) while
maximising the cost of the selected items. *(Solution: Selecting the pear and
apple gives the highest possible cost of 90.)* ::

    >>> from pyeasyga.pyeasyga import GeneticAlgorithm
    >>>
    >>> data = [('pear', 50), ('apple', 35), ('banana', 40)]
    >>> ga = GeneticAlgorithm(data, 20, 50, 0.8, 0.2, True, True)
    >>>
    >>> def create_individual(data):
    >>>     return [random.randint(0, 1) for _ in xrange(len(data))]
    >>>
    >>> ga.create_individual = create_individual
    >>>
    >>>
    >>> def crossover(parent_1, parent_2):
    >>>     crossover_index = random.randrange(1, len(parent_1))
    >>>     child_1 = parent_1[:index] + parent_2[index:]
    >>>     child_2 = parent_2[:index] + parent_1[index:]
    >>>     return child_1, child_2
    >>>
    >>> ga.crossover_function = crossover
    >>>
    >>>
    >>> def mutate(individual):
    >>>     mutate_index = random.randrange(len(individual))
    >>>     if individual[mutate_index] == 0:
    >>>         individual[mutate_index] = 1
    >>>     else:
    >>>         individual[mutate_index] = 0
    >>>
    >>> ga.mutate_function = mutate
    >>>
    >>>
    >>> def selection(population):
    >>>     return random.choice(population)
    >>>
    >>> ga.selection_function = selection
    >>>
    >>> def fitness (individual, data):
    >>>     fitness = 0
    >>>     if individual.count(1) == 2:
    >>>         for (selected, (fruit, profit)) in zip(individual, data):
    >>>             if selected:
    >>>                 fitness += profit
    >>>     return fitness
    >>>
    >>> ga.fitness_function = fitness
    >>> ga.run()
    >>> print ga.best_individual()
    >>>
    >>> for individual in ga.last_generation():
    >>>     print individual


text:
namespace unit_test
{
  class call_counter
  {
  public:
    call_counter()
      : m_counter(0)
    {
    }

    void inc() volatile
    {
      // memory_order_relaxed is enough for call counter
      m_counter.fetch_add(1, std::memory_order_relaxed);
    }

    size_t get() volatile const
    {
      return m_counter.load(std::memory_order_relaxed);
    }

    void reset() volatile
    {
      m_counter.store(0, std::memory_order_relaxed);
    }

  private:
    std::atomic<size_t> m_counter;
  };
}


text:
{% extends 'base.html' %}

{% block subtitle %}
  - Patient Merge
{% endblock %}

{% block content %}
    {{ message }}
{% endblock %}


text:
.PHONY: install

install:
	composer install

test:
	./console --quiet


text:
FOUNDATION_EXPORT double ASDataSyncVersionNumber;

//! Project version string for ASDataSync.
FOUNDATION_EXPORT const unsigned char ASDataSyncVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <ASDataSync/PublicHeader.h>

#import "ASManagedObjectContext.h"
#import "ASPublicProtocol.h"
#import "ASWatchConnector.h"
#import "NSManagedObject+ASDataSync.h"
#import "NSManagedObjectContext+SQLike.h"
#import "NSUUID+NSData.h"
#import "ASReference.h"


text:
@import url(./fontawesome/css/font-awesome.min.css);

@import url(./lato/init.css);

@import url(./pacifico/init.css);


text:
#pragma once
#ifndef KTN_MATH_MATRIX_H_
#define KTN_MATH_MATRIX_H_

#include "ktn/math/math.h"

namespace ktn { namespace math {

/*!
 @brief
 MxN Matrix
 */
template<class T, int M, int N=M>
class Matrix
{
    template<class FT, int FM, int FN>
    friend std::ostream& operator<<(std::ostream& os, const Matrix<FT, FM, FN>& m);
    //template<class FT, int FM, int FN>
    //friend std::istream& operator>>(std::istream& is, Matrix<FT, FM, FN>& m);

public:
    Matrix();
    Matrix(const T& t);
    Matrix(const Matrix<T, M, N>& b);
    virtual ~Matrix();

    static const Matrix<T, M, N> ZERO;
    static const Matrix<T, M, N> ONE;

    int row() const { return M; }
    int col() const { return N; }

    T& at(int x, int y);
    Matrix<T, N, M> t() const;

    bool operator!() const;
    Matrix<T, M, N> operator+() const;
    Matrix<T, M, N> operator-() const;

    Matrix<T, M, N> operator+(const Matrix<T, M, N>& m);
    Matrix<T, M, N> operator-(const Matrix<T, M, N>& m);
    Matrix<T, M, N> operator*(const T& n);

    template<int K>
    Matrix<T, K, N> operator*(const Matrix<T, K, M>& m);

    Matrix<T, M, N>& operator=(const Matrix<T, M, N>& m);
    Matrix<T, M, N>& operator+=(const Matrix<T, M, N>& m);
    Matrix<T, M, N>& operator-=(const Matrix<T, M, N>& m);
    Matrix<T, M, N>& operator*=(const T& n);

    bool operator==(const Matrix<T, M, N>& m) const;
    bool operator!=(const Matrix<T, M, N>& m) const;

//private:
    T** data_;
};

}} // namespace ktn math

#include "matrix.inl"

#endif // KTN_MATH_MATRIX_H_


text:
/*!
** @file ButtonStartStop.h
** @version 01.08
** @brief
**         The HAL GPIO component will provide a low level API for unified
**         access to general purpose digital input/output pins across
**         various device designs.
**
**         RTOS drivers using HAL GPIO API will be simpler and more
**         portable to various microprocessors.
*/
/*!
**  @addtogroup ButtonStartStop_module ButtonStartStop module documentation
**  @{
*/

#ifndef __ButtonStartStop_H
#define __ButtonStartStop_H

/* MODULE ButtonStartStop. */

/* Include shared modules, which are used for whole project */
#include "PE_Types.h"
#include "PE_Error.h"
#include "PE_Const.h"
#include "IO_Map.h"
/* Include inherited beans */
#include "IO_Map.h"
#include "GPIO_PDD.h"
#include "PORT_PDD.h"

#include "Cpu.h"

#ifdef __cplusplus
extern "C" {
#endif

/*! Peripheral base address of a device allocated by the component. This constant can be used directly in PDD macros. */
#define ButtonStartStop_PRPH_BASE_ADDRESS  0x400FF080U

/* Methods configuration constants - generated for all enabled component's methods */
#define ButtonStartStop_Init_METHOD_ENABLED /*!< Init method of the component ButtonStartStop is enabled (generated) */
#define ButtonStartStop_SetFieldValue_METHOD_ENABLED /*!< SetFieldValue method of the component ButtonStartStop is enabled (generated) */
#define ButtonStartStop_GetFieldValue_METHOD_ENABLED /*!< GetFieldValue method of the component ButtonStartStop is enabled (generated) */
#define ButtonStartStop_ClearFieldBits_METHOD_ENABLED /*!< ClearFieldBits method of the component ButtonStartStop is enabled (generated) */
#define ButtonStartStop_SetFieldBits_METHOD_ENABLED /*!< SetFieldBits method of the component ButtonStartStop is enabled (generated) */
#define ButtonStartStop_ToggleFieldBits_METHOD_ENABLED /*!< ToggleFieldBits method of the component ButtonStartStop is enabled (generated) */

/* Events configuration constants - generated for all enabled component's events */
#define ButtonStartStop_OnPortEvent_EVENT_ENABLED /*!< OnPortEvent event of the component ButtonStartStop is enabled (generated) */

/* Definition of bit field constants */
#define BUTTON_STARTSTOP ((LDD_GPIO_TBitField)0)

/* Definition of implementation constants */
#define ButtonStartStop_ALLOCATED_PINS_MASK 0x02U /*!< Mask of all allocated pins from the port */
#define ButtonStartStop_MODULE_BASE_ADDRESS PTC_BASE_PTR /*!< Name of macro used as the base address */
#define ButtonStartStop_PORTCONTROL_BASE_ADDRESS PORTC_BASE_PTR /*!< Name of macro used as the base address */
#define ButtonStartStop_AVAILABLE_EVENTS_MASK LDD_GPIO_ON_PORT_EVENT /*!< Mask of all available events */
#define ButtonStartStop_FIELD_0_PIN_0 LDD_GPIO_PIN_1 /*!< Constant for the pin in the field used in the method ConnectPin */
#define ButtonStartStop_BUTTON_STARTSTOP_START_BIT 1u /*!< Index of the starting bit of the bit field (0 represents LSB) */
#define ButtonStartStop_BUTTON_STARTSTOP_MASK 0x02u /*!< Mask of the bits allocated by the bit field (within the port) */
/* Representation of unaligned data value of the port.
   Unsigned integer of proper width depending on the size of the GPIO port allocated.
   Typically the value of n-th bit represents the data for the n-th pin within the port.
   Such value is not abstracted from the physical position of the bits within the port. */
typedef uint32_t ButtonStartStop_TPortValue;

/* Representation of right-aligned data value of the bit field.
   Typically the value of n-th bit represents the data of the n-th bit within the bit field (not within the port).
   There are used only so many lowest bits, as it is denoted by the width of the bit field.
   Such value is abstracted from the physical position of the bit field pins within the port.
   Equals to the type <compId>_TPortValue. */
typedef ButtonStartStop_TPortValue ButtonStartStop_TFieldValue;

/*
** ===================================================================
**     Method      :  ButtonStartStop_Init (component GPIO_LDD)
*/
/*!
**     @brief
**         This method initializes the associated peripheral(s) and the
**         component internal variables. The method is called
**         automatically as a part of the application initialization
**         code.
**     @param
**         UserDataPtr     - Pointer to the RTOS device
**                           structure. This pointer will be passed to
**                           all events as parameter.
**     @return
**                         - Pointer to the dynamically allocated private
**                           structure or NULL if there was an error.
*/
/* ===================================================================*/
LDD_TDeviceData* ButtonStartStop_Init(LDD_TUserData *UserDataPtr);

/*
** ===================================================================
**     Method      :  ButtonStartStop_SetFieldValue (component GPIO_LDD)
*/
/*!
**     @brief
**         This method sets the output data value of the specified bit
**         field.
**     @param
**         DeviceDataPtr   - Device data structure
**                           pointer returned by [Init] method.
**     @param
**         Field           - Bit field to write. Bit fields are
**                           defined during design time and for each bit
**                           field there is a generated constant.
**     @param
**         Value           - Aligned data value to writting to the
**                           specified bit field. The bit 0 corresponds
**                           with the pin which has index 0 within the
**                           given bit field, the bit 1 corresponds with
**                           the pin which has index 1 within the given
**                           bit field, etc.
*/
/* ===================================================================*/
void ButtonStartStop_SetFieldValue(LDD_TDeviceData *DeviceDataPtr, LDD_GPIO_TBitField Field, ButtonStartStop_TFieldValue Value);

/*
** ===================================================================
**     Method      :  ButtonStartStop_GetFieldValue (component GPIO_LDD)
*/
/*!
**     @brief
**         This method returns the current input data of the specified
**         field.
**     @param
**         DeviceDataPtr   - Device data structure
**                           pointer returned by [Init] method.
**     @param
**         Field           - Bit field to reading. Bit fields are
**                           defined during design time and for each bit
**                           field there is a generated constant.
**     @return
**                         - Aligned current port input value masked for
**                           allocated pins of the field. The bit 0
**                           corresponds with the pin which has index 0
**                           within the given bit field, the bit 1
**                           corresponds with the pin which has index 1
**                           within the given bit field, etc.
*/
/* ===================================================================*/
ButtonStartStop_TFieldValue ButtonStartStop_GetFieldValue(LDD_TDeviceData *DeviceDataPtr, LDD_GPIO_TBitField Field);

/*
** ===================================================================
**     Method      :  ButtonStartStop_ClearFieldBits (component GPIO_LDD)
*/
/*!
**     @brief
**         This method drives the specified bits of the specified bit
**         field to the inactive level.
**     @param
**         DeviceDataPtr   - Device data structure
**                           pointer returned by [Init] method.
**     @param
**         Field           - Bit field to write. Bit fields are
**                           defined during design time and for each bit
**                           field there is a generated constant.
**     @param
**         Mask            - Aligned mask of bits to setting the
**                           inactive level. Each field pin has
**                           corresponding bit in the mask. Bit value 0
**                           means not selected bit, bit value 1 means
**                           selected bit. The bit 0 corresponds with
**                           the pin which has index 0 within the given
**                           bit field, the bit 1 corresponds with the
**                           pin which has index 1 within the given bit
**                           field, etc.
*/
/* ===================================================================*/
void ButtonStartStop_ClearFieldBits(LDD_TDeviceData *DeviceDataPtr, LDD_GPIO_TBitField Field, ButtonStartStop_TFieldValue Mask);

/*
** ===================================================================
**     Method      :  ButtonStartStop_SetFieldBits (component GPIO_LDD)
*/
/*!
**     @brief
**         This method drives the specified bits of the specified bit
**         field to the active level.
**     @param
**         DeviceDataPtr   - Device data structure
**                           pointer returned by [Init] method.
**     @param
**         Field           - Bit field to write. Bit fields are
**                           defined during design time and for each bit
**                           field there is a generated constant.
**     @param
**         Mask            - Aligned mask of bits to setting the
**                           active level. Each field pin has
**                           corresponding bit in the mask. Bit value 0
**                           means not selected bit, bit value 1 means
**                           selected bit. The bit 0 corresponds with
**                           the pin which has index 0 within the given
**                           bit field, the bit 1 corresponds with the
**                           pin which has index 1 within the given bit
**                           field, etc.
*/
/* ===================================================================*/
void ButtonStartStop_SetFieldBits(LDD_TDeviceData *DeviceDataPtr, LDD_GPIO_TBitField Field, ButtonStartStop_TFieldValue Mask);

/*
** ===================================================================
**     Method      :  ButtonStartStop_ToggleFieldBits (component GPIO_LDD)
*/
/*!
**     @brief
**         This method inverts the specified bits of the specified bit
**         field to other level.
**     @param
**         DeviceDataPtr   - Device data structure
**                           pointer returned by [Init] method.
**     @param
**         Field           - Bit field to write. Bit fields are
**                           defined during design time and for each bit
**                           field there is a generated constant.
**     @param
**         Mask            - Aligned mask of bits to inverting the
**                           current level. Each field pin has
**                           corresponding bit in the mask. Bit value 0
**                           means not selected bit, bit value 1 means
**                           selected bit. The bit 0 corresponds with
**                           the pin which has index 0 within the given
**                           bit field, the bit 1 corresponds with the
**                           pin which has index 1 within the given bit
**                           field, etc.
*/
/* ===================================================================*/
void ButtonStartStop_ToggleFieldBits(LDD_TDeviceData *DeviceDataPtr, LDD_GPIO_TBitField Field, ButtonStartStop_TFieldValue Mask);

/*
** ===================================================================
**     Method      :  ButtonStartStop_Interrupt (component GPIO_LDD)
**
**     Description :
**         The method services the interrupt of the selected peripheral(s)
**         and eventually invokes event(s) of the component.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
/* {Default RTOS Adapter} ISR function prototype */
void ButtonStartStop_Interrupt(void);

/* END ButtonStartStop. */

#ifdef __cplusplus
}  /* extern "C" */
#endif

#endif
/* ifndef __ButtonStartStop_H */
/*!
** @}
*/
/*
** ###################################################################
**
**     This file was created by Processor Expert 10.5 [05.21]
**     for the Freescale Kinetis series of microcontrollers.
**
** ###################################################################
*/


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>If You Believe</title>
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/custom.css">

	<link rel="shortcut icon" href="https://micro.blog/curt/favicon.png" type="image/x-icon" />
  <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.xml" />

  <link rel="alternate" type="application/json" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.json" />
  <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />

  <link rel="me" href="https://micro.blog/curt" />

  	<link rel="me" href="https://twitter.com/curtclifton" />

  <link rel="authorization_endpoint" href="https://micro.blog/indieauth/auth" />
  <link rel="token_endpoint" href="https://micro.blog/indieauth/token" />
  <link rel="micropub" href="https://micro.blog/micropub" />
  <link rel="webmention" href="https://micro.blog/webmention" />
  <link rel="subscribe" href="https://micro.blog/users/follow" />

    Curt Clifton

    <time class="dt-published" datetime="2018-02-06 22:10:43 -0800">06 Feb 2018</time>

"If you believe in the rule of law, democratic norms and institutions and decent public debate, Republicans must pay a heavy, heavy price for indulging Trump." —Jennifer Rubin


text:
/* @version $Id: arguments.h 1196265 2011-11-01 20:43:52Z mturk $ */
#ifndef __JSVC_ARGUMENTS_H__
#define __JSVC_ARGUMENTS_H__

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * The structure holding all parsed command line options.
 */
typedef struct {
    /** The name of the PID file. */
    char *pidf;
    /** The name of the user. */
    char *user;
    /** The name of the JVM to use. */
    char *name;
    /** The JDK or JRE installation path (JAVA_HOME). */
    char *home;
    /** Options used to invoke the JVM. */
    char **opts;
    /** Number of JVM options. */
    int onum;
    /** The name of the class to invoke. */
    char *clas;
    /** Command line arguments to the class. */
    char **args;
    /** Number of class command line arguments. */
    int anum;
    /** Wether to detach from parent process or not. */
    bool dtch;
    /** Wether to print the VM version number or not. */
    bool vers;
    /** Show the VM version and continue. */
    bool vershow;
    /** Wether to display the help page or not. */
    bool help;
    /** Only check environment without running the service. */
    bool chck;
    /** Stop running jsvc */
    bool stop;
    /** number of seconds to until service started */
    int wait;
    /** Install as a service (win32) */
    bool install;
    /** Remove when installed as a service (win32) */
    bool remove;
    /** Run as a service (win32) */
    bool service;
    /** Destination for stdout */
    char *outfile;
    /** Destination for stderr */
    char *errfile;
    /** Program name **/
    char *procname;
    /** Whether to redirect stdin to /dev/null or not. Defaults to true **/
    bool redirectstdin;
    /** What umask to use **/
    int umask;
} arg_data;

/**
 * Parse command line arguments.
 *
 * @param argc The number of command line arguments.
 * @param argv Pointers to the different arguments.
 * @return A pointer to a arg_data structure containing the parsed command
 *         line arguments, or NULL if an error was detected.
 */
arg_data *arguments(int argc, const char *argv[]);

#ifdef __cplusplus
}
#endif
#endif                          /* ifndef __JSVC_ARGUMENTS_H__ */


text:
namespace content_settings {

// A content settings provider which manages settings defined by extensions.
class CustomExtensionProvider : public ObservableProvider,
                          public extensions::ContentSettingsStore::Observer {
 public:
  CustomExtensionProvider(
      extensions::ContentSettingsStore* extensions_settings,
      bool incognito);

  virtual ~CustomExtensionProvider();

  // ProviderInterface methods:
  virtual RuleIterator* GetRuleIterator(
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      bool incognito) const OVERRIDE;

  virtual bool SetWebsiteSetting(
      const ContentSettingsPattern& primary_pattern,
      const ContentSettingsPattern& secondary_pattern,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      Value* value) OVERRIDE;

  virtual void ClearAllContentSettingsRules(ContentSettingsType content_type)
      OVERRIDE {}

  virtual void ShutdownOnUIThread() OVERRIDE;

  // extensions::ContentSettingsStore::Observer methods:
  virtual void OnContentSettingChanged(const std::string& extension_id,
                                       bool incognito) OVERRIDE;

 private:
  // Specifies whether this provider manages settings for incognito or regular
  // sessions.
  bool incognito_;

  // The backend storing content setting rules defined by extensions.
  scoped_refptr<extensions::ContentSettingsStore> extensions_settings_;

  DISALLOW_COPY_AND_ASSIGN(CustomExtensionProvider);
};

}  // namespace content_settings

#endif  // CHROME_BROWSER_CONTENT_SETTINGS_CONTENT_SETTINGS_CUSTOM_EXTENSION_PROVIDER_H_


text:
import { EventEmitter } from 'events';

export const TodoStore = Object.assign({}, EventEmitter.prototype, {
    items: [],
    getAll() {
        return this.items;
    },
    addNewItemHandler(text) {
        this.items.push(text);
    },
    emitChange() {
        this.emit('change');
    },
    addChangeListener(callback) {
        this.on('change', callback);
    },
    removeChangeListener(callback) {
        this.removeListener('change', callback);
    }
});