text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="generator" content="Hugo 0.26" />

  <title>Posts · Sandors Systems Scribbles</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/grids-responsive-min.css">

  <link rel="stylesheet" href="https://theargo.io/css/side-menu.css">

  <link rel="stylesheet" href="https://theargo.io/css/blackburn.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" type="text/css">

  <link rel="alternate" type="application/rss+xml" title="Sandors Systems Scribbles" href="https://theargo.io/post/index.xml" />

  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/androidstudio.min.css">

  <link rel="shortcut icon" href="https://theargo.io/img/favicon.ico" type="image/x-icon" />

  Scribbles

          Posts

          About

          Home

      RSS

      Twitter

      GNU social

      LinkedIn

      GitHub

      Keybase

    © 2017. All rights reserved.

    Built with Hugo
    Theme Blackburn

Posts

2017

<time>10 Aug 2017, 00:00</time> - Git push to two remotes

2015

<time>08 Jul 2015, 00:00</time> - Configure new servers with the basics via Ansible

<time>18 May 2015, 00:00</time> - MacBook Setup Using Ansible and Homebrew

<time>01 May 2015, 00:00</time> - Deploy AWS Redshift into a dedicated VPC on the EC2-VPC platform

2014

<time>30 Nov 2014, 00:00</time> - Deploy Wordpress to AWS Beanstalk using eb

<time>03 Sep 2014, 00:00</time> - Run Ansible through pmksh

<time>03 Sep 2014, 00:00</time> - Ansible on HP-UX 11.31

<time>17 Jul 2014, 00:00</time> - Using Ansible to Align Passwords on Servers

<time>16 Jun 2014, 00:00</time> - Installing Ansible

<time>13 Jun 2014, 00:00</time> - Using Ansible to deploy a PuppetMaster

<time>01 Apr 2014, 00:00</time> - Using GoAccess to parse webserver logs

<time>12 Mar 2014, 00:00</time> - Dogecoin mining on Digital Ocean

2013

<time>20 Dec 2013, 00:00</time> - Using Oscar to Build a Local Puppet Environment with Vagrant

<time>17 Dec 2013, 00:00</time> - Using Vagrant on Windows

<time>10 Dec 2013, 00:00</time> - VPN Setup - OpenVPN Server Deploy on AWS

<time>10 Dec 2013, 00:00</time> - VPN Setup - MacBook to OpenVPN Server using Tunnelblick

<time>29 Nov 2013, 00:00</time> - Add WebProxy Cert to Fedora

<time>26 Nov 2013, 00:00</time> - Add Twitter Timeline to OctoPress Sidebar

<time>26 Nov 2013, 00:00</time> - Add Twitter Bootstrap 3 to OctoPress with OctoStrap3

<time>12 Nov 2013, 00:00</time> - Vanilla Vagrant Setup

<time>12 Nov 2013, 00:00</time> - Puppet vim setup

<time>12 Nov 2013, 00:00</time> - Post to octopress and deploy to Github pages

<time>12 Nov 2013, 00:00</time> - Auto Update VirtualBox Guest Additions with vagrant-vbguest

<time>03 Sep 2013, 00:00</time> - Ansible on RedHat 5.x


text:
====================
Pyex Multiprocessing
====================

Question
--------

Compute the factorial of a number. Demonstrate use of multiprocessing Pool.

Solution
--------

.. literalinclude:: ../../languages/python/algorithm_pyex_multiprocessing.py
   :language: python
   :tab-width: 4

.. runcode:: ../../languages/python/algorithm_pyex_multiprocessing.py
   :language: python
   :codesite: ideone

Explanation
===========

.. git_changelog::

.. seealso::

   * :python-suggest-improve:`algorithm_pyex_multiprocessing.py`
   * :python-better-explain:`algorithm_pyex_multiprocessing.rst`

redpajama_set_name: RedPajamaGithub


text:
module Mongoid #:nodoc:

  # This module contains the behaviour of Mongoid's clone/dup of documents.
  module Copyable
    extend ActiveSupport::Concern

    COPYABLES = [
      :attributes,
      :metadata,
      :changed_attributes,
      :previous_changes
    ]

    protected

    # Clone or dup the current +Document+. This will return all attributes with
    # the exception of the document's id and versions, and will reset all the
    # instance variables.
    #
    # This clone also includes embedded documents.
    #
    # @example Clone the document.
    #   document.clone
    #
    # @param [ Document ] other The document getting cloned.
    #
    # @return [ Document ] The new document.
    def initialize_copy(other)
      __copy__(other)
    end

    # Clone or dup the current +Document+. This will return all attributes with
    # the exception of the document's id and versions, and will reset all the
    # instance variables.
    #
    # This clone also includes embedded documents.
    #
    # @example Dup the document.
    #   document.dup
    #
    # @param [ Document ] other The document getting cloned.
    #
    # @return [ Document ] The new document.
    def initialize_dup(other)
      __copy__(other)
    end

    private

    # Handle the copy of the object.
    #
    # @api private
    #
    # @example Copy the object.
    #   document.__copy__(other)
    #
    # @param [ Document ] other The other document.
    #
    # @return [ Document ] self.
    #
    # @since 3.0.0
    def __copy__(other)
      other.as_document
      instance_variables.each { |name| remove_instance_variable(name) }
      COPYABLES.each do |name|
        value = other.send(name)
        instance_variable_set(:"@#{name}", value ? value.dup : nil)
      end
      attributes.delete("_id")
      if attributes.delete("versions")
        attributes["version"] = 1
      end
      @new_record = true
      identify
    end
  end
end


text:
<!DOCTYPE html>
<title>Canvas test: toDataURL.nocontext</title>

<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="toDataURL.arguments.3.html" title="toDataURL.arguments.3">
<link rel="next" href="toDataURL.zerosize.html" title="toDataURL.zerosize">

 <
 [index]
 >

toDataURL.nocontext

toDataURL works before any context has been got

References:

toDataURL.noarguments

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>


text:
module Database.Kafka.Core (
  connectProducer,
  connectConsumer,
  push,
  pull
) where

import Database.Kafka.Types (KafkaConfig, ProducerConfig, ConsumerConfig, TopicConfig, Consumer, Producer, Message)

connectProducer :: KafkaConfig -> ProducerConfig -> TopicConfig -> IO (Either String Producer)
connectProducer = error "Not Implemented"

connectConsumer :: KafkaConfig -> ConsumerConfig -> TopicConfig -> IO (Either String Consumer)
connectConsumer = error "Not Implemented"

push :: Producer -> Message k v -> IO (Either String ())
push = error "Not Implemented"

pull :: Consumer -> IO (Either String (Message k v))
pull = error "Not Implemented"


text:
package com.intellij.openapi.actionSystem.impl;

import com.intellij.ide.DataManager;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ModalityState;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

class ButtonToolbarImpl extends JPanel {
  private final DataManager myDataManager;
  private final String myPlace;
  private final PresentationFactory myPresentationFactory;
  private final ArrayList<ActionJButton> myActions = new ArrayList<>();

  ButtonToolbarImpl(@NotNull String place, @NotNull ActionGroup actionGroup) {
    super(new GridBagLayout());
    myPlace = place;
    myPresentationFactory = new PresentationFactory();
    myDataManager = DataManager.getInstance();

    initButtons(actionGroup);

    updateActions();
    ActionManagerEx.getInstanceEx().addTimerListener(500, new WeakTimerListener(new MyTimerListener()));
    enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
  }

  private void initButtons(@NotNull ActionGroup actionGroup) {
    final AnAction[] actions = actionGroup.getChildren(null);

    if (actions.length > 0) {
      int gridx = 0;

      add(// left strut
                Box.createHorizontalGlue(),
                new GridBagConstraints(gridx++, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                                        new Insets(8, 0, 0, 0), 0, 0));
      JPanel buttonsPanel = createButtons(actions);
      //noinspection UnusedAssignment
      add(buttonsPanel,
                new GridBagConstraints(gridx++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
                                       new Insets(8, 0, 0, 0), 0, 0));
    }
  }

  private JPanel createButtons(AnAction[] actions) {
    JPanel buttonsPanel = new JPanel(new GridLayout(1, actions.length, 5, 0));
    for (final AnAction action : actions) {
      ActionJButton button = new ActionJButton(action);
      myActions.add(button);
      buttonsPanel.add(button);
    }
    return buttonsPanel;
  }

  public JComponent getComponent() {
    return this;
  }

  private class ActionJButton extends JButton {
    private final AnAction myAction;

    ActionJButton(final AnAction action) {
      super(action.getTemplatePresentation().getText());
      myAction = action;
      setMnemonic(action.getTemplatePresentation().getMnemonic());
      setDisplayedMnemonicIndex(action.getTemplatePresentation().getDisplayedMnemonicIndex());

      addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          AnActionEvent event = new AnActionEvent(
            null,
            ((DataManagerImpl)DataManager.getInstance()).getDataContextTest(ButtonToolbarImpl.this),
            myPlace,
            myPresentationFactory.getPresentation(action),
            ActionManager.getInstance(),
            e.getModifiers()
          );
          if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) {
            ActionUtil.performActionDumbAware(action, event);
          }
        }
      });

    }

    public void updateAction(final DataContext dataContext) {
      AnActionEvent event = new AnActionEvent(
        null,
        dataContext,
        myPlace,
        myPresentationFactory.getPresentation(myAction),
        ActionManager.getInstance(),
        0
      );
      event.setInjectedContext(myAction.isInInjectedContext());
      myAction.update(event);
      setVisible(event.getPresentation().isVisible());
      setEnabled(event.getPresentation().isEnabled());
    }
  }

  private final class MyTimerListener implements TimerListener {
    @Override
    public ModalityState getModalityState() {
      return ModalityState.stateForComponent(ButtonToolbarImpl.this);
    }

    @Override
    public void run() {
      if (!isShowing()) {
        return;
      }

      Window mywindow = SwingUtilities.windowForComponent(ButtonToolbarImpl.this);
      if (mywindow != null && !mywindow.isActive()) return;

      // do not update when a popup menu is shown (if popup menu contains action which is also in the toolbar, it should not be enabled/disabled)
      final MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
      final MenuElement[] selectedPath = menuSelectionManager.getSelectedPath();
      if (selectedPath.length > 0) {
        return;
      }

      // don't update toolbar if there is currently active modal dialog

      final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
      if (window instanceof Dialog) {
        final Dialog dialog = (Dialog)window;
        if (dialog.isModal() && !SwingUtilities.isDescendingFrom(ButtonToolbarImpl.this, dialog)) {
          return;
        }
      }

      updateActions();
    }
  }

  private void updateActions() {
    final DataContext dataContext = ((DataManagerImpl)myDataManager).getDataContextTest(this);
    for (ActionJButton action : myActions) {
      action.updateAction(dataContext);
    }

    repaint();
  }
}


text:
package io.searchbox.core;

import com.google.gson.Gson;
import io.searchbox.action.AbstractAction;
import io.searchbox.action.AbstractMultiTypeActionBuilder;
import io.searchbox.core.search.sort.Sort;
import io.searchbox.params.Parameters;
import io.searchbox.params.SearchType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.*;

/**
 * @author Dogukan Sonmez
 * @author cihat keser
 */
public class Search extends AbstractAction<SearchResult> {

    private String query;
    private List<Sort> sortList = new LinkedList<Sort>();

    protected Search(Builder builder) {
        super(builder);

        this.query = builder.query;
        this.sortList = builder.sortList;
        setURI(buildURI());
    }

    @Override
    public SearchResult createNewElasticSearchResult(String responseBody, int statusCode, String reasonPhrase, Gson gson) {
        return createNewElasticSearchResult(new SearchResult(gson), responseBody, statusCode, reasonPhrase, gson);
    }

    public String getIndex() {
        return this.indexName;
    }

    public String getType() {
        return this.typeName;
    }

    @Override
    protected String buildURI() {
        return super.buildURI() + "/_search";
    }

    @Override
    public String getPathToResult() {
        return "hits/hits/_source";
    }

    @Override
    public String getRestMethodName() {
        return "POST";
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getData(Gson gson) {
        String data;
        if (sortList.isEmpty()) {
            data = query;
        } else {
            List<Map<String, Object>> sortMaps = new ArrayList<Map<String, Object>>(sortList.size());
            for (Sort sort : sortList) {
                sortMaps.add(sort.toMap());
            }

            Map rootJson = gson.fromJson(query, Map.class);
            rootJson.put("sort", sortMaps);
            data = gson.toJson(rootJson);
        }
        return data;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .appendSuper(super.hashCode())
                .append(query)
                .toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }

        Search rhs = (Search) obj;
        return new EqualsBuilder()
                .appendSuper(super.equals(obj))
                .append(query, rhs.query)
                .append(sortList, rhs.sortList)
                .isEquals();
    }

    public static class Builder extends AbstractMultiTypeActionBuilder<Search, Builder> {
        private String query;
        private List<Sort> sortList = new LinkedList<Sort>();

        public Builder(String query) {
            this.query = query;
        }

        public Builder setSearchType(SearchType searchType) {
            return setParameter(Parameters.SEARCH_TYPE, searchType);
        }

        public Builder addSort(Sort sort) {
            sortList.add(sort);
            return this;
        }

        public Builder addSort(Collection<Sort> sorts) {
            sortList.addAll(sorts);
            return this;
        }

        @Override
        public Search build() {
            return new Search(this);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="LargeTexture" inherits="Texture" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		[i]Deprecated.[/i] A [Texture] capable of storing many smaller textures with offsets.
	</brief_description>
	<description>
		[i]Deprecated (will be removed in Godot 4.0).[/i] A [Texture] capable of storing many smaller textures with offsets.
		You can dynamically add pieces ([Texture]s) to this [LargeTexture] using different offsets.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="add_piece">
			<return type="int" />
			<argument index="0" name="ofs" type="Vector2" />
			<argument index="1" name="texture" type="Texture" />
			<description>
				Adds [code]texture[/code] to this [LargeTexture], starting on offset [code]ofs[/code].
			</description>
		</method>
		<method name="clear">
			<return type="void" />
			<description>
				Clears the [LargeTexture].
			</description>
		</method>
		<method name="get_piece_count" qualifiers="const">
			<return type="int" />
			<description>
				Returns the number of pieces currently in this [LargeTexture].
			</description>
		</method>
		<method name="get_piece_offset" qualifiers="const">
			<return type="Vector2" />
			<argument index="0" name="idx" type="int" />
			<description>
				Returns the offset of the piece with the index [code]idx[/code].
			</description>
		</method>
		<method name="get_piece_texture" qualifiers="const">
			<return type="Texture" />
			<argument index="0" name="idx" type="int" />
			<description>
				Returns the [Texture] of the piece with the index [code]idx[/code].
			</description>
		</method>
		<method name="set_piece_offset">
			<return type="void" />
			<argument index="0" name="idx" type="int" />
			<argument index="1" name="ofs" type="Vector2" />
			<description>
				Sets the offset of the piece with the index [code]idx[/code] to [code]ofs[/code].
			</description>
		</method>
		<method name="set_piece_texture">
			<return type="void" />
			<argument index="0" name="idx" type="int" />
			<argument index="1" name="texture" type="Texture" />
			<description>
				Sets the [Texture] of the piece with index [code]idx[/code] to [code]texture[/code].
			</description>
		</method>
		<method name="set_size">
			<return type="void" />
			<argument index="0" name="size" type="Vector2" />
			<description>
				Sets the size of this [LargeTexture].
			</description>
		</method>
	</methods>
	<members>
		<member name="flags" type="int" setter="set_flags" getter="get_flags" overrides="Texture" default="0" />
	</members>
	<constants>
	</constants>
</class>


text:
namespace HuUtils.SystemManager
{
    partial class WMIInfo
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(49, 128);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(47, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "硬盘 ID";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(119, 125);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(182, 21);
            this.textBox1.TabIndex = 1;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(326, 123);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(157, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "获取硬盘ID";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // 硬盘信息获取
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(540, 304);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Name = "硬盘信息获取";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
    }
}


text:
Saving Throws

total

base

ability

misc

FORTITUDE
constitution

total

base

ability

misc

REFLEX
dexterity

total

base

ability

misc

WILL
wisdom

total

base

ability

misc


text:
<?php

declare(strict_types=1);

namespace Mwop\Art\Webhook;

use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\Mapper\Source\Source;
use CuyZ\Valinor\Mapper\TreeMapper;
use ImagickException;
use League\Flysystem\FilesystemException;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToWriteFile;
use Mwop\App\HomePageCacheExpiration;
use Mwop\Art\Photo;
use Mwop\Art\PhotoMapper;
use Mwop\Art\PhotoStorage;
use PDOException;
use Psr\Log\LoggerInterface;

use function sprintf;

class PayloadListener
{
    public function __construct(
        private PhotoStorage $photos,
        private PhotoMapper $mapper,
        private DatabaseBackup $backup,
        private TreeMapper $dataMapper,
        private LoggerInterface $logger,
        private ErrorNotifier $notifier,
        private HomePageCacheExpiration $expireHomePageCache,
    ) {
    }

    public function __invoke(Payload $payload): void
    {
        // Parse
        $photo = $this->parsePayloadJson($payload);
        if (null === $photo) {
            return;
        }

        // Upload
        $filename = $this->upload($photo);
        if (null === $filename) {
            return;
        }
        $photo->injectFilename($filename);

        // Create thumbnail
        $this->createThumbnail($filename, $photo);

        // Add to database
        if (! $this->insertIntoDatabase($photo)) {
            // Failed
            return;
        }

        ($this->expireHomePageCache)();

        // Backup database
        $this->backupDatabase();
    }

    private function parsePayloadJson(Payload $payload): ?Photo
    {
        try {
            return $this->dataMapper->map(Photo::class, Source::json($payload->json));
        } catch (MappingError $e) {
            $message = sprintf(
                "Unable to parse Instagram webhook payload, or invalid Instagram payload detected: %s\nPayload: %s",
                $e->getMessage(),
                $payload->json
            );
            $this->notifier->sendNotification($message);
            $this->logger->warning($message);

            return null;
        }
    }

    private function upload(Photo $photo): ?string
    {
        try {
            return $this->photos->upload($photo->sourceUrl);
        } catch (UnableToWriteFile | FilesystemException $e) {
            $message = sprintf(
                'Failed to upload Instagram photo (%s): %s',
                $photo->sourceUrl,
                $e->getMessage(),
            );
            $this->notifier->sendNotification($message);
            $this->logger->warning($message);
        }

        return null;
    }

    private function createThumbnail(string $filename, Photo $photo): void
    {
        try {
            $this->photos->createThumbnail($filename);
        } catch (ImagickException | UnableToWriteFile | FilesystemException $e) {
            $message = sprintf(
                'Failed to scale Instagram photo (%s:%s): %s',
                $photo->filename(),
                $photo->sourceUrl,
                $e->getMessage(),
            );
            $this->notifier->sendNotification($message);
            $this->logger->warning($message);
        }
    }

    private function insertIntoDatabase(Photo $photo): bool
    {
        try {
            $this->mapper->create($photo);
            return true;
        } catch (PDOException $e) {
            $message = sprintf(
                'Failed to create database record for (%s:%s): %s',
                $photo->filename(),
                $photo->sourceUrl,
                $e->getMessage(),
            );
            $this->notifier->sendNotification($message);
            $this->logger->warning($message);
        }

        return false;
    }

    private function backupDatabase(): bool
    {
        try {
            $this->backup->backup();
        } catch (UnableToCopyFile | FilesystemException $e) {
            $message = sprintf(
                'Unable to backup photo database: %s',
                $e->getMessage(),
            );
            $this->notifier->sendNotification($message);
            $this->logger->warning($message);
            return false;
        }

        return true;
    }
}


text:
@interface NewRecipeDetailController : BaseViewController
@property (nonatomic, copy) NSString *ID;
@end


text:
package org.apache.hadoop.hive.ql.ddl.table.storage.skewed;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLWork;
import org.apache.hadoop.hive.ql.ddl.DDLSemanticAnalyzerFactory.DDLType;
import org.apache.hadoop.hive.ql.ddl.table.AbstractAlterTableAnalyzer;
import org.apache.hadoop.hive.ql.ddl.table.AbstractAlterTableDesc;
import org.apache.hadoop.hive.ql.ddl.table.AlterTableType;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.PlanUtils;

import com.google.common.collect.Sets;

/**
 * Analyzer for set skewed location commands.
 */
@DDLType(types = HiveParser.TOK_ALTERTABLE_SKEWED_LOCATION)
public class AlterTableSetSkewedLocationAnalyzer extends AbstractAlterTableAnalyzer {
  public AlterTableSetSkewedLocationAnalyzer(QueryState queryState) throws SemanticException {
    super(queryState);
  }

  @Override
  protected void analyzeCommand(TableName tableName, Map<String, String> partitionSpec, ASTNode command)
      throws SemanticException {
    List<Node> locationNodes = command.getChildren();
    if (locationNodes == null) {
      throw new SemanticException(ErrorMsg.ALTER_TBL_SKEWED_LOC_NO_LOC.getMsg());
    }

    Map<List<String>, String> locations = new HashMap<>();
    for (Node locationNode : locationNodes) {
      List<Node> locationListNodes = ((ASTNode) locationNode).getChildren();
      if (locationListNodes == null) {
        throw new SemanticException(ErrorMsg.ALTER_TBL_SKEWED_LOC_NO_LOC.getMsg());
      }

      for (Node locationListNode : locationListNodes) {
        List<Node> locationMapNodes = ((ASTNode) locationListNode).getChildren();
        if (locationMapNodes == null) {
          throw new SemanticException(ErrorMsg.ALTER_TBL_SKEWED_LOC_NO_LOC.getMsg());
        }

        for (Node locationMapNode : locationMapNodes) {
          List<Node> locationMapNodeMaps = ((ASTNode) locationMapNode).getChildren();
          if ((locationMapNodeMaps == null) || (locationMapNodeMaps.size() != 2)) {
            throw new SemanticException(ErrorMsg.ALTER_TBL_SKEWED_LOC_NO_MAP.getMsg());
          }

          List<String> keyList = new LinkedList<String>();
          ASTNode node = (ASTNode) locationMapNodeMaps.get(0);
          if (node.getToken().getType() == HiveParser.TOK_TABCOLVALUES) {
            keyList = SkewedTableUtils.getSkewedValuesFromASTNode(node);
          } else if (isConstant(node)) {
            keyList.add(PlanUtils.stripQuotes(node.getText()));
          } else {
            throw new SemanticException(ErrorMsg.SKEWED_TABLE_NO_COLUMN_VALUE.getMsg());
          }

          String newLocation =
              PlanUtils.stripQuotes(unescapeSQLString(((ASTNode) locationMapNodeMaps.get(1)).getText()));
          validateSkewedLocationString(newLocation);
          locations.put(keyList, newLocation);
          outputs.add(toWriteEntity(newLocation));
        }
      }
    }

    AbstractAlterTableDesc desc = new AlterTableSetSkewedLocationDesc(tableName, partitionSpec, locations);
    setAcidDdlDesc(getTable(tableName), desc);
    addInputsOutputsAlterTable(tableName, partitionSpec, desc, AlterTableType.SET_SKEWED_LOCATION, false);
    rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(), desc)));
  }

  private static final Set<Integer> CONSTANT_TYPES = Sets.newHashSet(HiveParser.Number, HiveParser.StringLiteral,
      HiveParser.IntegralLiteral, HiveParser.NumberLiteral, HiveParser.CharSetName, HiveParser.KW_TRUE,
      HiveParser.KW_FALSE);

  private boolean isConstant(ASTNode node) {
    return CONSTANT_TYPES.contains(node.getToken().getType());
  }

  private void validateSkewedLocationString(String location) throws SemanticException {
    try {
      URI locationUri = new URI(location);
      if (!locationUri.isAbsolute() || locationUri.getScheme() == null || locationUri.getScheme().trim().equals("")) {
        throw new SemanticException(location + " is not absolute or has no scheme information. " +
            "Please specify a complete absolute uri with scheme information.");
      }
    } catch (URISyntaxException e) {
      throw new SemanticException(e);
    }
  }
}


text:
"use strict";
const fs = require("fs");
const jsdom = require("../..");
const toFileUrl = require("../util").toFileUrl(__dirname);

exports["Getting a file URL should work (from the same file URL)"] = t => {
  // From https://github.com/tmpvar/jsdom/pull/1180
  const window = jsdom.jsdom(undefined, { url: toFileUrl(__filename) }).defaultView;

  const xhr = new window.XMLHttpRequest();
  xhr.onload = () => {
    t.strictEqual(xhr.responseText, fs.readFileSync(__filename, { encoding: "utf-8" }));
    t.done();
  };

  xhr.open("GET", toFileUrl(__filename), true);
  xhr.send();
};

exports["Getting a file URL should have valid default response without setting responseType"] = t => {
  // From https://github.com/tmpvar/jsdom/pull/1183
  const window = jsdom.jsdom(undefined, { url: toFileUrl(__filename) }).defaultView;

  const xhr = new window.XMLHttpRequest();
  xhr.onload = () => {
    t.strictEqual(xhr.response, fs.readFileSync(__filename, { encoding: "utf-8" }));
    t.done();
  };

  xhr.open("GET", toFileUrl(__filename), true);
  xhr.send();
};

exports["Getting a file URL should not throw for getResponseHeader"] = t => {
  // From https://github.com/tmpvar/jsdom/pull/1180
  const window = jsdom.jsdom(undefined, { url: toFileUrl(__filename) }).defaultView;

  const xhr = new window.XMLHttpRequest();
  xhr.onload = () => {
    t.doesNotThrow(() => {
      t.strictEqual(xhr.getResponseHeader("Blahblahblah"), null);
    });
    t.done();
  };

  xhr.open("GET", toFileUrl(__filename), true);
  xhr.send();
};

exports["Getting a file URL should not throw for getAllResponseHeaders"] = t => {
  // From https://github.com/tmpvar/jsdom/pull/1183
  const window = jsdom.jsdom(undefined, { url: toFileUrl(__filename) }).defaultView;

  const xhr = new window.XMLHttpRequest();
  xhr.onload = () => {
    t.doesNotThrow(() => {
      t.strictEqual(xhr.getAllResponseHeaders(), "");
    });
    t.done();
  };

  xhr.open("GET", toFileUrl(__filename), true);
  xhr.send();
};


text:
require 'rails_helper'

feature 'Add a notifications api user' do

  let(:account) { create(:account) }
  let(:account_owner) { create(:account_owner, :account => account) }
  let!(:notifiable_app) { create(:app, :account => account) }

  before(:each) { login_as account_owner, :scope => :admin }

  scenario "Add a single notifications API user" do
    visit notifiable_admin.new_admin_account_notifications_api_user_path(account)
    fill_in 'notifications_api_user_service_name', :with => 'CRM'
    check "notifications_api_user_app_ids_#{notifiable_app.id}"
    click_button 'Create'

    expect(NotifiableAdmin::NotificationsApiUser.count).to eq 1
    expect(NotifiableAdmin::NotificationsApiUser.first.service_name).to eq 'CRM'
    expect(NotifiableAdmin::NotificationsApiUser.first.apps.count).to eq 1
    expect(NotifiableAdmin::NotificationsApiUser.first.account).to eq account
  end

  scenario "except without apps" do
    visit notifiable_admin.new_admin_account_notifications_api_user_path(account_owner.account)
    fill_in 'notifications_api_user_service_name', :with => 'CRM'
    click_button 'Create'

    expect(current_path).to eq notifiable_admin.new_admin_account_notifications_api_user_path(account_owner.account)
    expect(page).to have_content "Apps must include one at least one App"
  end

end


text:
import { getNestedProperty } from '../helpers';

const baseUrl = getNestedProperty( window.baseUrl, [ 'url' ] );
const images = Array.from( document.querySelectorAll( '.expandable' ) );

/**
 * Get full-sized image URL for the given attachment ID and
 * swap into given <img /> element.
 *
 * @param {object} img <img /> element to update src for
 * @param {string} id  Attachment ID to get full image URL for
 */
const fetchFullImage = ( img, id ) => {
	const url = `${ baseUrl }media/${ id }`;
	const xhr = new XMLHttpRequest();

	/**
	 * Request handler.
	 */
	xhr.onreadystatechange = () => {

		/**
		 * Only run once request is complete.
		 */
		if ( 4 !== xhr.readyState ) {
			return;
		}

		/**
		 * Run on successful request.
		 */
		if ( 200 <= xhr.status && 300 > xhr.status ) {
			const response = JSON.parse( xhr.response );
			const fullSrc = response.source_url;

			if ( fullSrc ) {
				const imgHeight = img.clientHeight;

				img.style.height = `${ imgHeight }px`;
				img.setAttribute( 'src', fullSrc );
			}
		} else {
			const error = JSON.parse( xhr.responseText );

			console.error( error.message );
		}
	}

	xhr.open( 'GET', url );
	xhr.send();
};

/**
 * Create modal element if it doesn't exist.
 *
 * @param {string} src        Image URL for initial <img /> src
 * @param {string} id         Attribute ID of image
 * @param {object} figcaption Caption element, if it exists
 */
const createModal = ( src, id, figcaption ) => {
	const modal = document.createElement( 'div' );
	const figure = document.createElement( 'figure' );
	const img = document.createElement( 'img' );
	const closeBtn = document.createElement( 'button' );
	const span = document.createElement( 'span' );
	const caption = figcaption ? figcaption.cloneNode( true ) : null;

	modal.className = 'modal';
	modal.setAttribute( 'id', `modal-${ id }` );

	img.setAttribute( 'src', src );
	img.classList.add( 'modal-image' );

	closeBtn.className = 'close';
	span.className = 'screen-reader-text';
	span.textContent = 'Close modal';

	closeBtn.appendChild( span );
	modal.addEventListener( 'click', ( e ) => {
		const element = e.target.tagName.toLowerCase();
		if ( element === 'div' || element === 'button' || element === 'figure' ) {
			modal.classList.remove( 'active' );
			document.documentElement.classList.remove( 'modal-open' );
		}
	 } );

	figure.appendChild( img );

	if ( caption ) {
		figure.appendChild( caption );
		img.classList.add( 'with-caption' );
	}

	modal.appendChild( figure );
	modal.appendChild( closeBtn );

	document.body.appendChild( modal );
	document.documentElement.classList.add( 'modal-open' );

	fetchFullImage( img, id );
	window.setTimeout( () => modal.classList.add( 'active' ) );
};

/**
 * Handle click event on image elements. Create or open modal.
 *
 * @param {event} e Click event.
 */
const handleClick = ( e ) => {
	const tag = e.target.tagName.toLowerCase();
	const img = e.currentTarget.querySelector( 'img' );

	if ( ! img || ( tag !== 'img' && tag !== 'figure' ) ) {
		return;
	}

	const id = img.className.split( '-' ).pop();
	const src = img.getAttribute( 'src' );
	const figcaption = img.nextElementSibling;
	const modal = document.getElementById( `modal-${ id }` );

	if ( modal ) {
		modal.classList.add( 'active' );
		document.documentElement.classList.add( 'modal-open' );
		return;
	} else {
		createModal( src, id, figcaption );
	}
};

export default () => {
	if ( ! baseUrl ) {
		return;
	}

	images.forEach( ( image ) => {
		image.addEventListener( 'click', handleClick );
	} );

	window.addEventListener( 'resize', () => {
		const resizeImages = Array.from( document.querySelectorAll( '.modal-image' ) );

		resizeImages.forEach( resizeImage => resizeImage.style.height = 'auto' );
	} );
};


text:
/* global define, require */
(function (root, factory) {
	'use strict';

	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['seriously'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		factory(require('seriously'));
	} else {
		if (!root.Seriously) {
			root.Seriously = { plugin: function (name, opt) { this[name] = opt; } };
		}
		factory(root.Seriously);
	}
}(window, function (Seriously) {
	'use strict';

	Seriously.plugin('crop', function () {
		var me = this;

		// custom resize method
		function resize() {
			var width = 1,
				height = 1,
				source = me.inputs.source,
				target,
				i;

			if (me.source) {
				width = me.source.width;
				height = me.source.height;
			} else if (me.sources && me.sources.source) {
				width = me.sources.source.width;
				height = me.sources.source.height;
			}

			width = width - me.inputs.left - me.inputs.right;
			height = height - me.inputs.top - me.inputs.bottom;

			width = Math.max(1, Math.floor(width));
			height = Math.max(1, Math.floor(height));

			if (me.width !== width || me.height !== height) {
				me.width = width;
				me.height = height;

				me.uniforms.resolution[0] = width;
				me.uniforms.resolution[1] = height;

				if (me.frameBuffer) {
					me.frameBuffer.resize(me.width, me.height);
				}

				me.emit('resize');
				me.setDirty();
			}

			for (i = 0; i < me.targets.length; i++) {
				target = me.targets[i];
				target.resize();
				if (target.setTransformDirty) {
					target.setTransformDirty();
				}
			}
		}

		me.resize = resize;

		return {
			commonShader: true,
			shader: function (inputs, shaderSource) {
				shaderSource.vertex = [
					'precision mediump float;',

					'attribute vec4 position;',
					'attribute vec2 texCoord;',

					'uniform vec2 resolution;',
					'uniform mat4 transform;',

					'uniform float top;',
					'uniform float left;',
					'uniform float bottom;',
					'uniform float right;',

					'varying vec2 vTexCoord;',

					'const vec2 ZERO = vec2(0.0);',
					'const vec2 ONE = vec2(1.0);',

					'void main(void) {',
					// first convert to screen space
					'	vec4 screenPosition = vec4(position.xy * resolution / 2.0, position.z, position.w);',
					'	screenPosition = transform * screenPosition;',

					// convert back to OpenGL coords
					'	gl_Position.xy = screenPosition.xy * 2.0 / resolution;',
					'	gl_Position.z = screenPosition.z * 2.0 / (resolution.x / resolution.y);',
					'	gl_Position.w = screenPosition.w;',

					'	vec2 dim = resolution + vec2(right + left, bottom + top);',
					'	vec2 scale = dim / resolution;',
					'	vec2 offset = vec2(left, bottom) / resolution;',

					'	vTexCoord = max(ZERO, (texCoord + offset) / scale);',
					'}\n'
				].join('\n');
				return shaderSource;
			},
			inputs: {
				source: {
					type: 'image',
					uniform: 'source',
					update: resize
				},
				top: {
					type: 'number',
					uniform: 'top',
					min: 0,
					step: 1,
					update: resize,
					defaultValue: 0
				},
				left: {
					type: 'number',
					uniform: 'left',
					min: 0,
					step: 1,
					update: resize,
					defaultValue: 0
				},
				bottom: {
					type: 'number',
					uniform: 'bottom',
					min: 0,
					step: 1,
					update: resize,
					defaultValue: 0
				},
				right: {
					type: 'number',
					uniform: 'right',
					min: 0,
					step: 1,
					update: resize,
					defaultValue: 0
				}
			}
		};
	},
	{
		inPlace: true,
		title: 'Crop'
	});
}));


text:
Qually is a web application that shows users jobs that match their qualifications. There are two ways qually determines what jobs a user is quallyfied for *years of experience* and *resume keywords*

## Desktop View
![Desktop screen shots](/desktop_view.png?raw=true "Desktop screen shots")

## Mobile View

![Mobile screen shots](/qually_mobile.png?raw=true "Mobile screen shots")

## Main Features
- Search for jobs
- Create a profile
- Save jobs

## Architecture
![ERD Diagram](/my_project_visualized.png?raw=true "ERD Diagram")

## Demo
| [Live Site](https://qually.herokuapp.com/) | [Video Demo](https://cl.ly/3m0j0o3w203F) |

## Technologies
 - Indeed API - communicates with Indeed to get a raw list of jobs for the user's job title and location
 - Python/Django
 - Postgresql
 - Bootstrap
 - AWS Elastic Beanstalk
 - Heroku

## What I Learned
**Big O isn't just for whiteboarding**:
An earlier version of this project was VERY slow. It took over 5 minutes to show the jobs list view after clicking "See My Jobs." The performance issues stemmed from the way I was finding the common keywords between the user's resume and each job description. The initial algorithm I used was very inefficient. For every word in a resume and every word in a job description, I checked every keyword from a database of keywords. If that word was a keyword and was in both the resume and job description, I saved it in a list of common keywords. These are the keywords that are displayed under a job blurb on the job list view. This algorithm is O(n^2), and it turned out to be very, very slow in practice.

To improve performance, I used a different approach. I constructed a dictionary of the words in a resume where the key was the word and the value was True. In python, keys that do not exist return a value of "None." Therefore, instead of looping through all of the words in a resume and checking them against words in a job description, I could just loop through the words in the job description, use each word as a key for the resume dictionary, and see if the value was true or None. That way I had the common words between a resume and a job description. I used a similiar approach and put all keywords from my database into a dictionary and checked the common words against the dictionary. Thus I reduced the time complexity of finding common keywords from O(n^2) to O(n). That ended up making a huge difference in practice, brining the time to see the job list view down to about 7 seconds.

**Take Time to Understand AWS Pricing/Database space isn't cheap**:
I had to take my site off of AWS because within 10 days of deployment it racked up a bill of over $200. I honestly didn't understand what I was being charged for (because I thought I was using the "Free Tier") and I didn't know how to reduce my bill, so I just shut it down. In the future, when I want to deploy a personal project using AWS, I'm going to make an effort to educate myself better on the costs so that I won't be caught off guard.

After I shut down my site, I looked into it and realized that my database size was driving the high costs. I had a large database because I was trying to increase performance by saving each job that Qually had seen already so that displaying the job list view could be faster. This is an example of the classic conflict between memory and time.

## Improvements
**Performance**:
Although I recently implemented some changes that have drastically reduced runtime, there is still much to be desired when it comes to performance. Most users expect an immediate result when they click a button, so in comparison 7 seconds seems VERY slow. To further improve performance, I'd like to experiment with Redis as a caching layer.

**Better Experience Filter**:
The experience filter uses a regular expression to identify both digits and numbers in word form and if a number is in the same sentence as the word "experience," then it assumes that this number represents how many years of experience the job requires. This crude approximation can be improved. Perhaps instead of looking at the entire sentence, it could only look three or four words after a number for the word experience. This would reduce the number of incorrect experience classifications.

**Resume Upload**:
I really wanted to look into being able to upload your resume (instead of copying and pasting it) but I didn't have time. It seems like Django has support for this already, and it would simply involve creating a model and view for Files.

**Asthetics**:
There are some visual things that I'd like to fix.
- footer with indeed credit should be flush to the bottom of the window
- profile view could look better on mobile
- some margin issues on job list view on some screens


text:
<!DOCTYPE html>

  <title>Article</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no,
  minimum-scale=1.0, maximum-scale=1.0, viewport-fit=cover">
  <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/paper/bootstrap.min.css" rel="stylesheet" integrity="sha384-awusxf8AUojygHf2+joICySzB780jVvQaVCAt1clU3QsyAitLGul28Qxb2r1e5g+" crossorigin="anonymous">
  <link href="css/style.css" rel="stylesheet">

Article

Source

Developers

About

Google

Space suit

Contents

Requirements

Theories of design

Contributing technologies

Models of significance

Emerging technologies

In fiction

See also

References

Bibliography

External links

A space suit is a garment worn to keep a human alive in the harsh environment of outer space, vacuum and temperature extremes. Space suits are often worn inside spacecraft as a safety precaution in case of loss of cabin pressure, and are necessary for extravehicular activity (EVA), work done outside spacecraft.

          Space suits have been worn for such work in Earth orbit, on the surface of the Moon, and en route back to Earth from the Moon. Modern space suits augment the basic pressure garment with a complex system of equipment and environmental systems designed to keep the wearer comfortable, and to minimize the effort required to bend the limbs, resisting a soft pressure garment's natural tendency to stiffen against the vacuum. A self-contained oxygen supply and environmental control system is frequently employed to allow complete freedom of movement, independent of the spacecraft.

Three types of spacesuits exist for different purposes: IVA (intravehicular activity), EVA (extravehicular activity), and IEVA (intra/extravehicular activity).IVA suits are meant to be worn inside a pressurized spacecraft, and are therefore lighter and more comfortable. IEVA suits are meant for use inside and outside the spacecraft, such as the Gemini G4C suit. They include more protection from the harsh conditions of space, such as protection from micrometeorites and extreme temperature change. EVA suits, such as the EMU, are used outside spacecraft, for either planetary exploration or spacewalks. They must protect the wearer against all conditions of space, as well as provide mobility and functionality.[1]

Some of these requirements also apply to pressure suits worn for other specialized tasks, such as high-altitude reconnaissance flight. At altitudes above the Armstrong limit, around 19,000 m (62,000 ft), water boils at body temperature and pressurized suits are needed.

The first full-pressure suits for use at extreme altitudes were designed by individual inventors as early as the 1930s.

The first space suit worn by a human in space was the Soviet SK-1 suit worn by Yuri Gagarin in 1961.

          Apollo A7L space suit worn by astronaut Buzz Aldrin on Apollo 11

            <canvas id="arapp" height=400></canvas>

          An interactive rendering of a space suit. Touch and drag to rotate, drag use two fingers to pan, pinch to zoom

          Orlan space suit, worn by astronaut Michael Fincke outside the International Space Station

          Text Source: Wikipedia | CC-BY-SA

3D Model Source: Google | CC-BY 3.0


text:
"""
Bilateral histogram.
"""

from __future__ import print_function
from __future__ import division

from halide import *

import numpy as np
from scipy.misc import imread, imsave
import os.path

int_t = Int(32)
float_t = Float(32)

def get_bilateral_grid(input, r_sigma, s_sigma):

    x = Var('x')
    y = Var('y')
    z = Var('z')
    c = Var('c')

    # Add a boundary condition
    clamped = Func('clamped')
    clamped[x, y] = input[clamp(x, 0, input.width()-1),
                          clamp(y, 0, input.height()-1)]

    # Construct the bilateral grid
    r = RDom(0, s_sigma, 0, s_sigma, 'r')
    val = clamped[x * s_sigma + r.x - s_sigma//2, y * s_sigma + r.y - s_sigma//2]
    val = clamp(val, 0.0, 1.0)
    #zi = cast(int_t, val * (1.0/r_sigma) + 0.5)
    zi = cast(int_t, (val / r_sigma) + 0.5)
    histogram = Func('histogram')
    histogram[x, y, z, c] = 0.0
    histogram[x, y, zi, c] += select(c == 0, val, 1.0)

    # Blur the histogram using a five-tap filter
    blurx, blury, blurz = Func('blurx'), Func('blury'), Func('blurz')
    blurz[x, y, z, c] = histogram[x, y, z-2, c] + histogram[x, y, z-1, c]*4 + histogram[x, y, z, c]*6 + histogram[x, y, z+1, c]*4 + histogram[x, y, z+2, c]
    blurx[x, y, z, c] = blurz[x-2, y, z, c] + blurz[x-1, y, z, c]*4 + blurz[x, y, z, c]*6 + blurz[x+1, y, z, c]*4 + blurz[x+2, y, z, c]
    blury[x, y, z, c] = blurx[x, y-2, z, c] + blurx[x, y-1, z, c]*4 + blurx[x, y, z, c]*6 + blurx[x, y+1, z, c]*4 + blurx[x, y+2, z, c]

    # Take trilinear samples to compute the output
    val = clamp(clamped[x, y], 0.0, 1.0)
    zv = val / r_sigma
    zi = cast(int_t, zv)
    zf = zv - zi
    xf = cast(float_t, x % s_sigma) / s_sigma
    yf = cast(float_t, y % s_sigma) / s_sigma
    xi = x/s_sigma
    yi = y/s_sigma
    interpolated = Func('interpolated')
    interpolated[x, y, c] = lerp(lerp(lerp(blury[xi, yi, zi, c], blury[xi+1, yi, zi, c], xf),
                                   lerp(blury[xi, yi+1, zi, c], blury[xi+1, yi+1, zi, c], xf), yf),
                              lerp(lerp(blury[xi, yi, zi+1, c], blury[xi+1, yi, zi+1, c], xf),
                                   lerp(blury[xi, yi+1, zi+1, c], blury[xi+1, yi+1, zi+1, c], xf), yf), zf)

    # Normalize
    bilateral_grid = Func('bilateral_grid')
    bilateral_grid[x, y] = interpolated[x, y, 0]/interpolated[x, y, 1]

    target = get_target_from_environment()
    if target.has_gpu_feature():
    #if True:
        # GPU schedule
        # Currently running this directly from the Python code is very slow.
        # Probably because of the dispatch time because generated code
        # is same speed as C++ generated code.
        print ("Compiling for GPU.")
        histogram.compute_root().reorder(c, z, x, y).gpu_tile(x, y, 8, 8);
        histogram = histogram.update() # Because returns ScheduleHandle
        histogram.reorder(c, r.x, r.y, x, y).gpu_tile(x, y, 8, 8).unroll(c)
        blurx.compute_root().gpu_tile(x, y, z, 16, 16, 1)
        blury.compute_root().gpu_tile(x, y, z, 16, 16, 1)
        blurz.compute_root().gpu_tile(x, y, z, 8, 8, 4)
        bilateral_grid.compute_root().gpu_tile(x, y, s_sigma, s_sigma)
    else:
        # CPU schedule
        print ("Compiling for CPU.")
        histogram.compute_root().parallel(z)
        histogram = histogram.update() # Because returns ScheduleHandle
        histogram.reorder(c, r.x, r.y, x, y).unroll(c)
        blurz.compute_root().reorder(c, z, x, y).parallel(y).vectorize(x, 4).unroll(c)
        blurx.compute_root().reorder(c, x, y, z).parallel(z).vectorize(x, 4).unroll(c)
        blury.compute_root().reorder(c, x, y, z).parallel(z).vectorize(x, 4).unroll(c)
        bilateral_grid.compute_root().parallel(y).vectorize(x, 4)

    return bilateral_grid

def generate_compiled_file(bilateral_grid):

    target = get_target_from_environment()
    # Need to copy the filter executable from the C++ apps/bilateral_grid folder to run this.
    # (after making it of course)
    arguments = ArgumentsVector()
    arguments.append(Argument('r_sigma', InputScalar, Float(32), 0))
    arguments.append(Argument('input', InputBuffer, UInt(16), 2))
    bilateral_grid.compile_to_file("bilateral_grid",
                                   arguments,
                                   target)
    print("Generated compiled file for bilateral_grid function.")
    return

def get_input_data():

    image_path = os.path.join(os.path.dirname(__file__), "../../apps/images/rgb.png")
    assert os.path.exists(image_path), \
        "Could not find %s" % image_path
    rgb_data = imread(image_path)
    #print("rgb_data", type(rgb_data), rgb_data.shape, rgb_data.dtype)

    grey_data = np.mean(rgb_data, axis=2, dtype=np.float32)
    input_data = np.copy(grey_data, order="F") / 255.0
    # input is in [0, 1] range
    #print("input_data", type(input_data), input_data.shape, input_data.dtype)

    return input_data

def filter_test_image(bilateral_grid, input):

    bilateral_grid.compile_jit()

    # preparing input and output memory buffers (numpy ndarrays)
    input_data = get_input_data()
    input_image = Image(input_data)
    input.set(input_image)

    output_data = np.empty(input_data.shape, dtype=input_data.dtype, order="F")
    output_image = Image(output_data)

    if False:
        print("input_image", input_image)
        print("output_image", output_image)

    # do the actual computation
    bilateral_grid.realize(output_image)

    # save results
    input_path = "bilateral_grid_input.png"
    output_path = "bilateral_grid.png"
    imsave(input_path, input_data)
    imsave(output_path, output_data)
    print("\nbilateral_grid realized on output_image.")
    print("Result saved at '", output_path,
          "' ( input data copy at '", input_path, "' ).", sep="")

    return

def main():

    input = ImageParam(float_t, 2, 'input')
    r_sigma = Param(float_t, 'r_sigma', 0.1) # Value needed if not generating an executable
    s_sigma = 8 # This is passed during code generation in the C++ version

    #print("r_sigma", r_sigma)

    bilateral_grid = get_bilateral_grid(input, r_sigma, s_sigma)

    # Set `generate` to False to run the jit immediately and get  instant gratification.
    #generate = True
    generate = False
    if generate:
        generate_compiled_file(bilateral_grid)
    else:
        filter_test_image(bilateral_grid, input)

    print("\nEnd of game. Have a nice day!")
    return

if __name__ == '__main__':
    main()


text:
<!doctype html>
<title>TextTrackList.getTrackById</title>


text:
/**
 * Injectable Objects that contains a live list of child directives in the light Dom of a directive.
 * The directives are kept in depth-first pre-order traversal of the DOM.
 *
 * In the future this class will implement an Observable interface.
 * For now it uses a plain list of observable callbacks.
 *
 * @exportedAs angular2/view
 */
export declare class BaseQueryList<T> {
    protected _results: List<T>;
    protected _callbacks: any[];
    protected _dirty: boolean;
    [Symbol.iterator](): IterableIterator<T>;
    reset(newList: any): void;
    add(obj: any): void;
    fireCallbacks(): void;
    onChange(callback: any): void;
    removeCallback(callback: any): void;
    length: number;
    first: any;
    last: any;
}


text:
<?php

//No Direct Access
defined('_JEXEC') or die;

/* Params */
$moduleid_sfx = htmlspecialchars($params->get('moduleid_sfx'));

//store params as object that we can loop through in tmpl/default.php
$slideritems = array();
$data_slide = 8;
for ($i = 1; $i <= $data_slide; $i++) {
    $slideritems[$i]['caption'] = $params->get("slide" . $i . "_caption");
    $slideritems[$i]['image'] = $params->get("slide" . $i . "_image");
    $slideritems[$i]['link'] = $params->get("slide" . $i . "_link");
}

if(empty($moduleid_sfx)){
    $moduleid_sfx ='myCarousels';
}
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';

require JModuleHelper::getLayoutPath('mod_multiplecarousel', $params->get('layout', 'default'));
?>


text:
Version control is something that I'm sure most are familiar with (if not check out this tutorial and this course), but something that you may not be familiar with is how to optimize a Unity Project for Git version control.

One issue is that within a Unity Project there are many folders and files that can remain local and don't need to be tracked. The Library folder, for instance, when not present is always constructed on load, while OS (Mac/Windows etc.) specific files don't need to be synced across computers.

Firstly, in Project Settings/Editor insure Version Control Mode is set to Visible Meta Files

![](images/gitVersionControl1.png)

as this is required for version control. The benefit of this meta files is that unique settings for a file (such as import settings for a sprite etc.) are saved to an associated meta file, so syncing is easier and faster between projects.

Now we could commit only the relevant files (that is, the Assets and ProjectSettings folders)
```
git add Assets
git add ProjectSettings
```
but one issue is the annoyance of untracked files messages for files which we have no interest in tracking.

![](images/gitVersionControl2.png)

Luckily by writing a custom .gitignore file (saved to the root project folder), we can specific the files that git should ignore tracking.

```
# Unity generated folders
Temp/
Library/

# Custom Build Folder
Builds/

# MonoDevelop generated files
obj/
*.csproj
*.unityproj
*.sln
*.userprefs

# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
```

![](images/gitVersionControl3.png)

One last point is the Editor setting Asset Serialization Mode to being Force Text or Mixed (between Text and Binary). Most Unity Projects will have scenes, prefabs and thus a lot of binary files. Force Text works better for version control in viewing the changes between commits, but Mixed means that binary files are imported faster into the project.


text:
namespace Vidly.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class AddMoviesAndGenresTables : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Movies",
                c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Title = c.String(),
                    GenreId = c.Int(),
                })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Genres", t => t.GenreId)
                .Index(t => t.GenreId);

            CreateTable(
                "dbo.Genres",
                c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                })
                .PrimaryKey(t => t.Id);
        }

        public override void Down()
        {
            DropForeignKey("dbo.Movies", "GenreId", "dbo.Genres");
            DropIndex("dbo.Movies", new[] { "GenreId" });
            DropTable("dbo.Genres");
            DropTable("dbo.Movies");
        }
    }
}


text:
The tests.

```csharp
public IReadOnlyList<ConformanceTestInfo>? Tests { get; set; }
```

## See Also

* class [ConformanceTestInfo](../ConformanceTestInfo.md)
* class [ConformanceApiTesterSettings](../ConformanceApiTesterSettings.md)
* namespace [Facility.ConformanceApi.Testing](../../Facility.ConformanceApi.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.ConformanceApi.dll -->


text:
This is a [Babel](https://babeljs.io/) plugin adds support for hygienic, non-syntactic macros for JavaScript.

[![Build Status](https://travis-ci.org/codemix/babel-plugin-macros.svg)](https://travis-ci.org/codemix/babel-plugin-macros)

[![NPM](https://nodei.co/npm-dl/babel-plugin-macros.png?months=1)](https://nodei.co/npm/babel-plugin-macros/)

> Note: Now requires Babel 6.

# What?

Turns code like this:
```js
DEFINE_MACRO(MAP, (input, visitor) => {
  const length = input.length;
  const result = new Array(length);
  for (let i = 0; i < length; i++) {
    result[i] = visitor(input[i], i, input);
  }
  return result;
});

function demo () {
  return MAP([1,2,3,4], item => item + 1);
}
```
Into code like this:
```js
function demo() {
  var _input = [1, 2, 3, 4];
  var _map = undefined;

  var _length = _input.length;
  var _result = new Array(_length);
  for (var _i2 = 0; _i2 < _length; _i2++) {
    _result[_i2] = _input[_i2] + 1;
  }
  _map = _result;

  return _map;
}
```

Also you may use more native syntax to define macro
```js
macro: function MACRO() {
  console.log('MACRO called');
}
MACRO();
```

Macro calls can also be chained, so if you declare a new macro called, e.g. `FILTER`:

```js
DEFINE_MACRO(FILTER, (input, visitor) => {
  const filtered = [];
  for (let i = 0; i < input.length; i++) {
    if (visitor(input[i], i, input)) {
      filtered.push(input[i]);
    }
  }
  return filtered;
});
```

You'll then be able to combine the two macros in one statement, without needing to nest:
```js
MAP([1, 2, 3], item => item + 1).FILTER(item => item < 4).length; // 2
```

# Why?

Because macros are incredibly useful! Also because they make it easy to write extremely fast code without sacrificing readability. When compiled with [closure elimination](https://github.com/codemix/babel-plugin-closure-elimination) the above code is [10x faster](http://jsperf.com/macros-vs-functions) than native `Array.prototype.map()`.

# Note: This is super experimental, use at your own risk!

# Todo List

- [ ] Allow macros in macro definitions (currently causes infinite loop)
- [ ] Allow macros to be imported and exported across files.
- [ ] Add `DEFINE_TRANSFORM` which is similar to `DEFINE_MACRO` but allows direct AST manipulation, not merely replacement.

# Installation

First, install via [npm](https://npmjs.org/package/babel-plugin-macros).
```sh
npm install --save-dev babel-plugin-macros
```
Then, in your babel configuration (usually in your `.babelrc` file), add `"macros"` to your list of plugins:
```json
{
  "plugins": ["macros"]
}
```

# ChangeLog
- **0.0.1** base implementation
- **1.0.0** update for babel@6 API
- **1.0.1** fix npm package
- **1.0.2** fix crash when missed some arguments
- **1.0.3** fix behavior of same-name macros in different scopes.
   before this change same-name macros are re-declared.
   now macros in different scopes - are different macros.
- **1.0.4** fix wrong scoping for equal-named macros
fix combining more than 2 macros
- **1.0.5** optimization. Replacement `traverse` to `get` to find the desired node
- **1.0.6** honest exception for infinite recursion in macros
- **1.0.7** add checking types in runtime
- **1.0.8** block using `this` and `arguments` in macros
- **1.0.9** fix multiple `return` & `return` without value
- **1.0.10** optimize performance of compile. x10 at tests
- **1.0.11** depedency for lodash no more needed
- **1.0.12** new syntax for define macro, using label
- **1.0.13** Implement function inlining for macro arguments
- **1.0.14** fix for different inlined function types in macro-argument
- **1.0.15** fix crash for case if babel-core use same babel-traverse, but in own sub-directory (without npm dedupe)

# License

Published by [codemix](http://codemix.com/) under a permissive MIT License, see [LICENSE.md](./LICENSE.md).


text:
Warning notice
===============
This project has not been updated for a long time, proceed with caution and **give stars 🌟 to @redth for making this amazing library**. :)

PushSharp-Anywhere
===============

This project demonstrates the usage/implementation of the PushSharp .NET SDK for simple and efficient management of multiplatform (IOS, Android and Windows Phone) Push Notification services on the server side.

This solution is consisted from a couple of separate projects including shared processor libraries; a Web .NET WebAPI    app and a Desktop Windows Forms app used for monitoring and handling push notifications as a "state machine".

The repo is also planned to have more (iOS Obj-C, Android, Win RT 8.1, Win10 UWP, Xamarin.iOS, Xamarin.Android, Xamarin.Forms) client implementations connecting to an PushSharp service server.

ATTENTION: Take care of how much PushNotification objects you will read from the database when processing, in this case there is a thread looping/pooling the database for one per one of the newst push notifications. You could also set to read all the notifications instead of one (latest). For more info jump into the code of the PushNotificationProcessor.cs file.

Instruction for use
===============
Server: Enter all connection strings to your database where needed, register for push notifications on the service providers: Google, Apple and Microsoft, enter the provided keys to PushNotificationProcessor.cs.

Clients: Enter your 3rd party server endpoints in the proper places/classes.

Disclaimer
===============
This project was built for a show case on the mscommunity.hr standup/meetup in Zagreb held at 25.11.2014. No coded tests were performed, bugs are possible, please contribute and fork on!

Update 23.9.2015.
===============
Project was updated for the conference MobilityDay 2015 showcase. Take care when loading the Android app, needs gradle reconfiguration.


text:
require 'appflight/version'
require 'appflight/web'
require 'pry'


text:
import { ADD_TODO } from '../constants/ActionTypes';

const initialState = [{
  text: 'First Item',
  marked: false,
  id: 0,
}];

export default function todos(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return [{
        id: (state.length === 0) ? 0 : state[0].id+1,
        marked: false,
        text: action.text,
      }, ...state];

    default:
      return state;
  }
}


text:
List

<button class="btn btn-primary" (click)="toggleView()">Toggle View</button>
<button class="btn btn-primary" (click)="diagnostics()">Diagnose</button>

            {{ transaction.datePosted }} ({{ transaction.id }})
            {{ transaction.description }} - {{ transaction.value }}

    <transaction-table *ngIf="!showTable" [transactions]="transactions"></transaction-table>


text:
<?php
/**
 * Contains the Taglib_Utils class.
 * @package com.thomaspwilson.taglibengine
 */
/**
 * Taglib_Utils contains miscellaneous functions that really don't fit anywhere
 * else.
 *
 * @author Thomas P. Wilson <thomas@thomaspwilson.com>
 * @copyright Thomas P. Wilson 2010-2011
 * @license http://www.opensource.org/licenses/mit-license MIT License
 * @package com.thomaspwilson.taglibengine
 * @since April 10, 2010
 */
class Taglib_Utils {
    public static function escapeXml($string) {
        return htmlspecialchars($string, ENT_QUOTES);
    }

    public static function unescapeXml($string) {
        return str_replace(
            array('&', '&quot', '&#039', '<', '>'),
            array('&', '"', "'", '<', '>'), $string);
    }

    public static function findFirstOf($subject, $chars, $offset = 0) {
        $r = false;
        for ($i = 0, $max = strlen($chars); $i < $max; $i++) {
            if (($p = strpos($subject, $chars[$i], $offset)) === false) continue;
            if ($p == $offset) return $p;
            if (($p < $r) || ($r === false)) $r = $p;
        }
        return $r;
    }
}

?>


text:
/**
 * @file
 **/

#pragma once

#include <vector>

#include "modules/common/math/qp_solver/qp_solver.h"
#include "modules/planning/math/smoothing_spline/spline_1d_solver.h"
#include "osqp/osqp.h"

namespace apollo {
namespace planning {

class OsqpSpline1dSolver : public Spline1dSolver {
 public:
  OsqpSpline1dSolver(const std::vector<double>& x_knots, const uint32_t order);
  virtual ~OsqpSpline1dSolver();

  bool Solve() override;

  void CleanUp();

  void ResetOsqp();

 private:
  OSQPSettings* settings_ = nullptr;
  OSQPWorkspace* work_ = nullptr;  // Workspace
  OSQPData* data_ = nullptr;       // OSQPData
};

}  // namespace planning
}  // namespace apollo


text:
package com.javarush.task.task35.task3510;

public class Dog {

    protected String name;

    public Dog(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Пес " + name;
    }
}


text:
default:
	bash ./scripts/init.sh

convert:
	rm data/short-abstracts_en.xml
	cat data/short-abstracts_en.nt | scripts/filterNtToCsv-regex.py > data/short-abstracts_en.xml

benchmark-convert:
	echo "Benchmarking python filter: 10000 lines/triples (Slow)"
	head -10000 data/short-abstracts_en.nt | time scripts/filterNtToCsv.py 1> data/short-abstracts_en-10000.csv 2> pythonFilter.bench
	rm data/short-abstracts_en-10000.csv

	echo "Benchmarking string filter: 10000 lines/triples (Fast)"
	head -10000 data/short-abstracts_en.nt | time scripts/filterNtToCsv-regex.py 1> data/short-abstracts_en-10000.xml 2> pythonFilter-regex.bench
	rm data/short-abstracts_en-10000.xml

run-solr: remove-dbpedia-core
	solr/bin/solr start -m 8G
	solr/bin/solr create_core -c dbpedia-abstracts-solr -d solr/server/solr/configsets/basic_configs
	solr/bin/post -c dbpedia-abstracts-solr data/short-abstracts_en.xml

stop-solr:
	solr/bin/solr stop

remove-dbpedia-core:
	rm -rf solr/server/solr/dbpedia-abstracts-solr


text:
using System;

namespace Azure.ResourceManager.KubernetesConfiguration.Models
{
    /// <summary> Parameters to authenticate using Service Principal. </summary>
    public partial class ServicePrincipalPatchDefinition
    {
        /// <summary> Initializes a new instance of ServicePrincipalPatchDefinition. </summary>
        public ServicePrincipalPatchDefinition()
        {
        }

        /// <summary> The client Id for authenticating a Service Principal. </summary>
        public string ClientId { get; set; }
        /// <summary> The tenant Id for authenticating a Service Principal. </summary>
        public Guid? TenantId { get; set; }
        /// <summary> The client secret for authenticating a Service Principal. </summary>
        public string ClientSecret { get; set; }
        /// <summary> Base64-encoded certificate used to authenticate a Service Principal. </summary>
        public string ClientCertificate { get; set; }
        /// <summary> The password for the certificate used to authenticate a Service Principal. </summary>
        public string ClientCertificatePassword { get; set; }
        /// <summary> Specifies whether to include x5c header in client claims when acquiring a token to enable subject name / issuer based authentication for the Client Certificate. </summary>
        public bool? ClientCertificateSendChain { get; set; }
    }
}


text:
function usingMoreFunctions() {
var str = userLang();
var b = str.search(/en/i);
if (b == -1) {
var useCM = true;
} else {
var useCM = false;
}
if (useCM == true) {
var inpCM = prompt('How tall are you (in CM)');
} else {
var inpINCH = prompt('How tall are you (in INCH)');
}
if (isset(inpCM)) {
var ans = convert(inpCM, 'cm', 'inch');
var ans2 = convert(inpCM, 'cm', 'm');
alert("You're " + ans + " inch long that's " + ans2 + " meter");
} else if (isset(inpINCH)) {
var ans = convert(inpINCH, 'inch', 'cm');
var ans2 = convert(inpCM, 'inch', 'm');
alert("You're " + ans + " cm long that's " + ans2 + " meter");
}
alert('The following functions where used \n\n\tuserLang \n\t\tWhy? \n\t\t\tTo see which measurement system you use\n\tisset \n\t\tWhy? \n\t\t\tTo see what was set\n\tconvert \n\t\tWhy? \n\t\t\tTo convert inch to centimeter (or centimetre to inch) and inch/centimetre to meter\n');
return true;
}


text:
<?php

namespace M3rten\DoubleOptIn;

use Illuminate\Support\ServiceProvider;

class DoubleOptInServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        #include __DIR__ . '/routes.php';
        $this->loadViewsFrom(__DIR__.'/views', 'doubleoptin');

        $this->publishes([
            __DIR__.'/views' => base_path('resources/views/vendor/doubleoptin'),
        ]);

        $this->loadTranslationsFrom(__DIR__.'/lang', 'doubleoptin');

        $this->publishes([
            __DIR__.'/lang' => base_path('resources/lang/vendor/doubleoptin'),
        ]);

        $this->publishes([
            __DIR__.'/database/migrations' => database_path('migrations'),
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
import scala.reflect.macros.whitebox._
import scala.language.experimental.macros

abstract class MyContext extends Context

class Bundle(val c: MyContext) {
  import c.universe._
  def impl = q"()"
}

object Macros {
  def foo: Any = macro Bundle.impl
}


text:
using Lithogen.Core;
using Lithogen.Core.Interfaces;
using BassUtils;

namespace Lithogen.TestSite1.Plugins
{
    /// <summary>
    /// This class exists simply to test that loading of plugins
    /// from within the website works. It should show up in the Output window
    /// (assuming you have a mapping established).
    /// </summary>
    public class EmbeddedProcessor : IProcessor
    {
        const string LOG_PREFIX = "EmbeddedProcessor: ";
        readonly ILogger TheLogger;

        public EmbeddedProcessor(ILogger logger)
        {
            TheLogger = logger.ThrowIfNull("logger");
        }

        public void Process(IPipelineFile file)
        {
            file.ThrowIfNull("file");

            TheLogger.LogMessage(LOG_PREFIX + "Running...");
        }
    }
}


text:
"use strict";
import React from 'react'

export default class extends React.Component {
  render() {
    let item = this.props.item;
    if (this.props.type === 'binary' ) {
      if (!item)
        return ;
      else if (item.split("/")[0] === 'data:image')
        return ;
      else
        return Download;
    } else if (this.props.type === 'boolean' ) {
      return {item?'true':'false'};
    } else {
      return {item||'-'};
    }
  }
}


text:
vaadin_cookbook
===============

Code based upon the examples in the Vaadin 7 Cookbook [1].

The code is either my own or copied from the examples provided via the books code download [2].

All files are released under The Apache License, version 2 [3].

The full license is included in file named LICENSE.

---
Organisation
------------
The project has a parent pom.xml which references children, one for each chapter.  Chapters are named ChapterXX where XX corresponds the the Chapter number.

Each child (chapter) has all the examples in it for that chapter.  Naming is free form but once followed the convention of chXX_loremIpsum.

---
Creating a subproject
---------------------
Do
```shell
./createMavenProject.sh <artifactId> <ChapterNumber>
```

E.g.

```shell
./createMavenProject.sh ch03_insertBtn Chapter03
```

From the vaadin_cookbook diretory.

Sorry to create a new chapter, you'll need to do it manually.

---

[1] Holaň, J; Kvasnovský O (2013). Vaadin 7 Cookbook. Birmingham: Packt Publishing. All.

[2] Holaň, J; Kvasnovský O. (2013). Vaadin 7 Cookbook Download. Available: http://www.packtpub.com/support/11498. Last accessed 2nd June 2014.

[3] The Apache Softaware Foundation (2004). Apache License, Version 2.0. Available: http://www.apache.org/licenses/LICENSE-2.0. Last accessed 5th June 2014.


text:
'use strict';

//TODO: wth is Bloodhound
//TODO: this is especially messy

/**
 * @fileoverview Autocomplete search related functions
 * @author JoshJRogan@gmail.com (Josh Rogan)
 * @author ritwikg2004@live.com (Ritwik Gupta)
 * @author jjnaughton93@gmail.com (JJ Naughton)
 */
module.exports = (function() {
    let util = require('./util');

    let autocomplete = {
        debug: true,
        inputSelector: '#search-bar-auto',
        resultsSelector: '.autocomplete-results',
        resultsSizeMax: 10, //The limit of how many results to show in the list
        database: []
    };

    /**
     * @return {[type]} [description]
     */
    /*
    autocomplete.init = function() {
        $(autocomplete.resultsSelector).slideUp();
        this.typeahead();
        this.isFormula = util.isFormula;
        this.isINCHI = util.isINCHI;
    };
     */

    /**
     * Tokenize a formula by breaking into it's molecular components
     * @param  {String} formula string representing a formula
     * @return {ARray}         tokenized results
     */
    /*
    autocomplete.formulaTokenizer = function(formula) {
        formula = formula.toLowerCase();
        var splitFormula = formula.replace(/([a-z])/g, ' $1').trim();
        var tokens = splitFormula ? splitFormula.split(/\s+/) : [];
        tokens.push(formula); //Add the full string
        return tokens;
    };
     */

    /**
     * Sort all of the items this happens in search and after filter
     * @param  {[type]} a [description]
     * @param  {[type]} b [description]
     * @return {[type]}   [description]
     */
    /*
    autocomplete.suggestionSorter = function(suggestions, query){
        var isFormula = this.isFormula(query);
        var noNumbers = query.match(/\d+/g) === null;
        suggestions = this.filter(suggestions, query);
        var topSuggestions = [];
        var topFormulas = [];
        suggestions = $.map(suggestions, function(value){
            //Difficult to tell before 3
            if(query.length > 2){
                //Prioritize Name
                if(noNumbers || !isFormula){
                    if(query === value.name.substring(0,query.length)
                        .toLowerCase()){
                        topSuggestions.push(value);
                        return null;
                    }
                }
            }
            //Prioritieze formulas by length
            if(query.length > 2 && isFormula){
                if(query === value.formula.substring(0,query.length)
                    .toLowerCase()){
                    // top_formulas.push(value);
                    // return null;
                }
            }
            return value;
        });

        //Add top name suggestions by closest match
        if(topSuggestions.length){
            topSuggestions.sort(function(a,b) {
                return b.name.length - a.name.length;
            });
            $.each(topSuggestions, function(index, obj){
                suggestions.unshift(obj);
            });
        }
        //Add top formula suggestions by closest match
        if(topFormulas.length){
            //Shortest formulas first
            topFormulas.sort(function(a,b) {
                return b.formula.length - a.formula.length;
            });

            $.each(topFormulas, function(index, obj){
                suggestions.unshift(obj);
            });
        }

        return suggestions.slice(0,this.resultsSizeMax);
    };
    */

    /*
    autocomplete.filter = function(suggestions, query){
        var isFormula = this.isFormula(query);
        var isINCHI = this.isINCHI(query);
        var seenInchis = [];
        suggestions = $.map(suggestions, function(value){

            //Remove duplicate inchi values
            if(seenInchis.indexOf(value.inchikey) < 0){
                seenInchis.push(value.inchikey);
            }
            else{
                return null;
            }
            //Remove long names if they aren't formula or inchi
            if(!isINCHI && !isFormula && value.name.length > 20){
                return null;
            }
            /*
            //TODO: this was commented out
            //Length shortner
            if( value.name.length > 20 || value.name.match(/[,-]/g) === null){
                // return null;
            }
            return value;
        });
        return suggestions;
    };
    */

    /**
     * Setup typeahead for autocomplete and suggested search
     * @return {[type]} [description]
     */
    /*
    autocomplete.typeahead = function() {
        var data = autoComplete;
        this.engine = new Bloodhound({
            datumTokenizer: function(data) {
                // console.log(data);
                var nameTokens = Bloodhound.tokenizers.whitespace(data.name);
                var formulaTokens = autocomplete.formulaTokenizer(data.formula);
                var synonymTokens = data.synonyms; //Already in an array
                var tagsTokens = data.tags; //Already in an array
                var inchiTokens = data.inchikey; //Just one value
                //Quickly disabled tokens
                // nameTokens = [];
                // formulaTokens = [];
                // synonymTokens = [];
                tagsTokens = []; //Producing too many results
                //Combine all of the tokens
                return nameTokens.concat(formulaTokens).concat(synonymTokens)
                    .concat(tagsTokens).concat(inchiTokens);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            local: auto_complete,
            remote: {
                url: "/suggestions?partial=%QUERY",
                wildcard: '%QUERY'
            },
            cache: true,
            identify: function(obj){
                return obj.inchikey
            },
            // sorter: this.suggestionSorter
        });
        //Seperate engine for low ranking items
        this.lowRank = new Bloodhound({
            datumTokenizer: function(data) {
                var synonymTokens = data.synonyms;
                var tagsTokens = data.tags;
                synonymTokens = [];
                tagsTokens = [];
                //Combine all of the tokens
                return synonymTokens.concat(tagsTokens);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            local: auto_complete,
            identify: function(obj){
                return obj.inchikey;
            },
        });

        this.TypeAhead = $(this.inputSelector).typeahead({
            hint: false,
            minLength: 1,
            classNames: {
                dataset: 'autocomplete-results',
                suggestion: 'suggestion',
            }
        }, {
            name: 'name',
            display: 'name',
            limit: 1000,
            // source: this.engine,
            source: function(query, sync, async) {
                autocomplete.engine.search(
                    query,
                    function(suggestions) {
                        sync(autocomplete.suggestionSorter(suggestions,
                            query.toLowerCase()));
                    },
                    function(suggestions){
                        async(autocomplete.suggestionSorter(suggestions,
                            query.toLowerCase()));
                    }
                );
            },
            templates: {
                empty: function(data){
                    return "

Zero results. Search for <samp class='font-red'>" + data.query + "</samp>

";
                },
                suggestion: function(data) {
                    return autocomplete.renderHTML(data);
                },
                pending: `

`,
            }
        });
        //If using the keyboard following links on select
        this.TypeAhead.bind('typeahead:select', function(ev, suggestion) {
            var element = $('.autocomplete-results [data-inchi="' +
            suggestion.inchikey + '"] a');
            if(element.length){
                element[0].click();
            }
        });
    };
    */

    /**
     * Create an object to allow auto complete
     * @return Object An object containing data to determine search results
     */
    /*
    autocomplete.getData = function() {
        var object = {};
        // return object;
        return this.placeholderDatabase;
    };
    */

    /**
     * Render the HTML for one result to be added to the DOM
     * @param  {Object} result Parse the object and generate HTMl
     * @return {String} HTML string to be added to the Dom
     */
    /*
    autocomplete.renderHTML = function(result) {
        var formula = result.formula.replace(/(\d+)/g, "$1");
        var html = '
' +
            '' +
            '
' +
            '' +
            '
 ' +
            '
' +
            '
' + result.name.substring(0, 36).toProperCase()+ '
' +
            '
' +  formula + '
' +
        '
' +
        '' +
        '
 ';

        return html;
    };
    */

    return autocomplete;
})();


text:
yes,I'am here.

learn more about yourself , accept yourself . And improve day by day .
think deeper , share opinion with others .


text:
/**
 *
 */
#include "application.h"

#include <iostream>

#include "config.h"
#include "SDL.h"
#include "SDL_syswm.h"

#include "window/window.h"

/*************************************/
vaApplication::vaApplication() :
	m_appError(AE_NO_ERROR),
	m_appName(APP_NAME_STR),
	m_appVersion(APP_VERSION_STR),
	m_sdlVersion(0u),
	m_sdlVersionString("\0") {
}

/*************************************/
int vaApplication::Run() {
	if(InitSDL()) {
		std::cout << "Running" << std::endl;
	}

	vaWindow engineWnd;
	engineWnd.Init();
	if (engineWnd.IsValid()) {
		engineWnd.Run();
	}

	SDL_Quit();
	return m_appError;
}

/*************************************/
bool vaApplication::InitSDL() {
	const int resSDLInit = SDL_Init(0);
	if (resSDLInit != 0) {
		SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize SDL: %s", SDL_GetError());
		m_appError = AE_SDL_INIT_FAILED;
	} else {
		SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s version : %s\n", m_appName, m_appVersion);
		SDL_SysWMinfo info;
		SDL_VERSION(&info.version);

		m_sdlVersion = info.version.major << 16;
		m_sdlVersion |= info.version.minor << 8;
		m_sdlVersion |= info.version.patch;
		std::snprintf(m_sdlVersionString, sdlVersionBufferSize,
		 "%d.%d.%d", (int)info.version.major, (int)info.version.minor, (int)info.version.patch);

		SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Running SDL version %s", m_sdlVersionString);
	}
	return resSDLInit;
}


text:
#Requires -Version 3.0

. "$($PSScriptRoot)\..\..\TestInitialize.ps1"

Describe 'Debug-SPClientObject' {

    Context 'Success' {

        It 'Dumps a site' {
            $Web = $SPClient.ClientContext.Site.OpenWebById($SPClient.TestConfig.WebId)
            $SPClient.ClientContext.Load($Web)
            $SPClient.ClientContext.ExecuteQuery()
            $Params = @{
                InputObject = $Web
            }
            $Result = Debug-SPClientObject @Params
            $Result | Should Not BeNullOrEmpty
            $Result | Should BeOfType 'System.Collections.Generic.Dictionary`2[string,object]'
        }

        It 'Dumps a list collection' {
            $Web = $SPClient.ClientContext.Site.OpenWebById($SPClient.TestConfig.WebId)
            $ListCollection = $Web.Lists
            $SPClient.ClientContext.Load($ListCollection)
            $SPClient.ClientContext.ExecuteQuery()
            $Params = @{
                InputObject = $ListCollection
            }
            $Result = Debug-SPClientObject @Params
            $Result | Should Not BeNullOrEmpty
            $Result | Should BeOfType 'System.Collections.Generic.Dictionary`2[string,object]'
        }

        It 'Dumps a site with hierarchy' {
            $Web = $SPClient.ClientContext.Site.OpenWebById($SPClient.TestConfig.WebId)
            $SPClient.ClientContext.Load($Web)
            $SPClient.ClientContext.Load($Web.RootFolder)
            $SPClient.ClientContext.Load($Web.Lists)
            $SPClient.ClientContext.ExecuteQuery()
            $Params = @{
                InputObject = $Web
            }
            $Result = Debug-SPClientObject @Params
            $Result | Should Not BeNullOrEmpty
            $Result | Should BeOfType 'System.Collections.Generic.Dictionary`2[string,object]'
        }

        It 'Dumps a list item' {
            $Web = $SPClient.ClientContext.Site.OpenWebById($SPClient.TestConfig.WebId)
            $List = $Web.Lists.GetById($SPClient.TestConfig.ListId)
            $ListItem = $List.GetItemById($SPClient.TestConfig.ListItemId)
            $SPClient.ClientContext.Load($ListItem)
            $SPClient.ClientContext.ExecuteQuery()
            $Params = @{
                InputObject = $ListItem
            }
            $Result = Debug-SPClientObject @Params
            $Result | Should Not BeNullOrEmpty
            $Result | Should BeOfType 'System.Collections.Generic.Dictionary`2[string,object]'
        }

    }

}


text:
---
layout:			post
date:				2016-05-10 18:16
title:			Laver la vaisselle avec un raton-laveur
subtitle:
categories:	[ménage]
tags:				[vaisselle, animaux, bicarbonate-de-soude, biodégradable, couverture-de-survie]
---

# Ceci est un article de test avec un très long titre de premier niveau pour tester le line-height des titres

Voici un 3ème article de test pour les drafts. Le deuxième n'apparaissait pas dans le [site local](http://alt-escape.github.io) donc j'essaie d'en faire un troisième pour voir ce qu'il se passe.

*Au passage j'ai enlevé le [paramètre](https://www.google.com) «published: false;» du 2ème draft pour qu'il apparaisse dans la liste des articles.*

## Avec un titre de 2ème niveau pour faire joli avec un très long titre de deuxième niveau pour tester le line-height des titres et blablabla et bla bla bla bla bla bla

Généralement, on utilise un texte en faux latin (le texte ne veut rien dire, il a été modifié), le Lorem ipsum ou Lipsum, qui permet donc de faire office de texte d'attente. L'avantage de le mettre en latin est que **l'opérateur sait au premier coup d'oeil que la page contenant ces lignes n'est pas valide**, et surtout l'attention du client n'est pas dérangée par le contenu, ***il demeure concentré*** seulement sur l'aspect graphique.

![Texte alternatif de l'image](/images/image_test.jpg "Texte de <tag> de l'image")
*Voici la légende de l'image ci-dessus. C'est une très belle image qui donne toute sa splendeur à l'article.*

Généralement, on utilise un texte en faux latin (le texte ne veut rien dire, il a été modifié), le Lorem ipsum ou Lipsum, qui permet donc de faire office de texte d'attente.

> QUOTE: Généralement, on utilise un texte en faux latin (le texte ne veut rien dire, il a été modifié), le Lorem ipsum ou Lipsum, qui permet donc de faire office de texte d'attente. L'avantage de le mettre en latin est que **l'opérateur sait [au premier coup d'oeil](http://www.google.com) que la page contenant ces lignes n'est pas valide**, et surtout l'attention du client n'est pas dérangée par le contenu, ***il demeure concentré*** seulement sur l'aspect graphique.

### Titre de 3ème niveau avec un très long titre de troisième niveau pour tester le line-height des titres et blablabla et bla bla bla bla bla bla

Ce texte a pour autre avantage d'utiliser des mots de longueur variable, [essayant de simuler une occupation normale](http://www.google.com). La méthode simpliste consistant à copier-coller un court texte plusieurs fois (« ceci est un faux-texte ceci est un faux-texte ceci est un faux-texte ceci est un faux-texte ceci est un faux-texte ») a l'inconvénient de ne pas permettre une juste appréciation typographique du résultat final.

## Et encore un titre de 2ème niveau

### Et un p'tit titre de 3ème niveau pour comparer

``` scss
/* this is a multiline comment */
// this is a one-line comment
.hello {
	background-color: rgba(235,22,89,.1);
	margin: 0 0 1rem;
}
```
``` html
<a href="url">Link text</a>
<p>Généralement, on utilise un texte en faux latin (le texte ne veut rien dire, il a été modifié), le Lorem ipsum ou Lipsum, qui permet donc de faire office de texte d'attente. </p>
```

L'avantage de le mettre en latin est que l'opérateur sait au premier coup d'oeil que la page contenant ces lignes n'est pas valide, et surtout l'attention du client n'est pas ```dérangée``` par le contenu, il demeure concentré seulement sur l'aspect graphique.

Et voici une magnifique liste de choses:

1. Première chose
2. Deuxième chose
	1. Première chose du 2e niveau
	2. Deuxième chose du 2e niveau
3. Troisème chose
4. Quatrième chose
	1. Première chose du 2e niveau
	2. Deuxième chose du 2e niveau
		1. Première chose du 3e niveau
5. Cinquième chose
6. Sixième chose

- Première chose
- Deuxième chose
	- Première chose du 2e niveau
	- Deuxième chose du 2e niveau
- Troisème chose
	- Première chose du 2e niveau
	- Deuxième chose du 2e niveau
		- Première chose du 3e niveau

#### Titre de 4ème niveau

Il circule des centaines de versions différentes du *Lorem ipsum*,

#### Un autre titre de 4ème niveau avec un très long titre de quatrième niveau pour tester le line-height des titres et blablabla et bla bla bla bla bla bla

mais ce texte aurait originellement été tiré de l'ouvrage de Cicéron, De Finibus Bonorum et Malorum (Liber Primus, 32), texte populaire à cette époque, dont l'une des premières phrases

#### Et encore un parce qu'on peut

est : « Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... »

#### Allez! Un dernier pour la route ;)

(« Il n'existe personne qui aime la souffrance pour elle-même, ni qui la recherche ni qui la veuille pour ce qu'elle est... »).


text:
package com.udacity.gamedev.drawthecantorgasket;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;

/*

TODO: Start here

The Cantor gasket is a fractal where we start with a white square. We divide that square up into a 3x3 grid of smaller squares, then remove the middle square. Finally, we repeat the process on each of the remaining 8 squares.

 */

public class DrawTheCantorGasket extends ApplicationAdapter {

    // TODO: Set a constant for how many recursions to draw
    private final static int RECURSIONS = 5;
    ShapeRenderer shapeRenderer;

    @Override
    public void create() {
        shapeRenderer = new ShapeRenderer();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Rectangle bounds = findLargestSquare();

        // TODO: Begin a filled shapeRenderer batch
        shapeRenderer.begin(ShapeType.Filled);

        // TODO: Draw a white square matching the bounds
        shapeRenderer.setColor(Color.WHITE);
        shapeRenderer.rect(bounds.x, bounds.y, bounds.width, bounds.height);

        // TODO: Set the working color to black, and call punchCantorGasket with the bounds
        shapeRenderer.setColor(Color.BLACK);
        punchCantorGasket(bounds.x, bounds.y, bounds.width, RECURSIONS);

        // TODO: End the batch
        shapeRenderer.end();
    }

    @Override
    public void resize(int width, int height) {
        shapeRenderer = new ShapeRenderer();
    }

    private void punchCantorGasket(float x, float y, float size, int recursions) {
        // TODO: Base case, if recursions = 0, return
        if (recursions == 0) {
            return;
        }

        float newSize = size / 3f;
        float newSize2 = newSize * 2;

        // TODO: Draw a black square in the middle square
        shapeRenderer.rect(x + newSize, y + newSize, newSize, newSize);

        recursions--;

        // TODO: Call punchCantorGasket on all 8 other squares
        punchCantorGasket(x, y, newSize, recursions); // 0,0
        punchCantorGasket(x, y + newSize, newSize, recursions); // 0,1
        punchCantorGasket(x, y + newSize2, newSize, recursions); // 0,2

        punchCantorGasket(x + newSize, y, newSize, recursions); // 1,0
        punchCantorGasket(x + newSize, y + newSize2, newSize, recursions); // 1, 2

        punchCantorGasket(x + newSize2, y, newSize, recursions); // 2,0
        punchCantorGasket(x + newSize2, y + newSize, newSize, recursions); // 2,1
        punchCantorGasket(x + newSize2, y + newSize2, newSize, recursions); // 2,2

        // Here's a more compact way to perform the recursive calls.
        // Thanks to GitHub user khafan! https://github.com/khafan

//        for (int i = 0; i < 9; i++) {
//            if (i == 4) continue;
//            punchCantorGasket(i%3 * newSize + x, i/3 * newSize + y, newSize, recursions);
//        }
    }

    private Rectangle findLargestSquare() {
        Rectangle largestSquare = new Rectangle();
        float screenWidth = Gdx.graphics.getWidth();
        float screenHeight = Gdx.graphics.getHeight();

        Gdx.app.log("Derp",  "Screen size " + screenWidth + " " + screenHeight);

        if (screenWidth > screenHeight) {
            largestSquare.x = (screenWidth - screenHeight) / 2;
            largestSquare.y = 0;
            largestSquare.width = screenHeight;
            largestSquare.height = screenHeight;
        } else {
            largestSquare.x = 0;
            largestSquare.y = (screenHeight - screenWidth) / 2;
            largestSquare.width = screenWidth;
            largestSquare.height = screenWidth;
        }
        return largestSquare;
    }
}