text:
package com.cpxiao.androidutils.library.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

/**
 * SoundPoolUtils
 * 可播放文件格式:wav
 * 不能播放:
 *
 * @author cpxiao on 2016/5/7
 */
public class SoundPoolUtils {

    private SoundPoolUtils() {
    }

    /**
     * 双重校验锁单例模式,注意不要遗漏volatile关键字
     */
    private static volatile SoundPoolUtils soundPoolUtils = null;

    public static SoundPoolUtils getInstance() {
        if (soundPoolUtils == null) {
            synchronized (SoundPoolUtils.class) {
                if (soundPoolUtils == null) {
                    soundPoolUtils = new SoundPoolUtils();
                }
            }
        }
        return soundPoolUtils;
    }

    /**
     * SoundPool
     */
    private SoundPool mSoundPool;

    /**
     * 音效是否加载完成
     */
    private boolean isSoundPoolLoaded = false;

    /**
     * 资源map
     */
    private HashMap<Integer, Integer> mHashMap = new HashMap<>();

    private class PlaySound extends Thread {
        private int soundId = -1;

        public PlaySound(int id) {
            soundId = id;
        }

        @Override
        public void run() {
            playSound(soundId);
        }

        private void playSound(int id) {
            if (isSoundPoolLoaded) {
                mSoundPool.play(id, 1, 1, 1, 0, 1);
            }
        }
    }

    /**
     * 播放
     *
     * @param key key
     */
    public void play(Integer key) {
        if (mHashMap != null) {
            try {
                int id = mHashMap.get(key);
                new PlaySound(id).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建SoundPool
     *
     * @param maxStreams maxStreams
     */
    public void createSoundPool(int maxStreams) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            createNewSoundPool(maxStreams);
        } else {
            createOldSoundPool(maxStreams);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void createNewSoundPool(int maxStreams) {
        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_GAME)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();
        mSoundPool = new SoundPool.Builder()
                .setAudioAttributes(attributes)
                .setMaxStreams(maxStreams)
                .build();
    }

    @SuppressWarnings("deprecation")
    private void createOldSoundPool(int maxStreams) {
        mSoundPool = new SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0);
    }

    /**
     * 加载音效
     *
     * @param context context
     * @param resId   resId
     * @param key     key
     */
    private void loadSound(Context context, int resId, Integer key) {
        if (mSoundPool != null) {
            int id = mSoundPool.load(context, resId, 1);
            Log.d("CPXIAO", "id = " + id);
            mHashMap.put(key, id);
        }
    }

    /**
     * 加载音效
     *
     * @param context context
     * @param map     音效源
     */
    public void loadSound(Context context, HashMap<Integer, Integer> map) {
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer key = entry.getKey();
            int id = entry.getValue();
            loadSound(context, id, key);
        }

        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                isSoundPoolLoaded = true;    //  表示加载完成
            }
        });

    }
}


text:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>2D Sierpinski Gasket</title>

<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;

void
main()
{
    gl_Position = vPosition;
}
</script>

<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;

void
main()
{
    gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}
</script>

<script type="text/javascript" src="../Common/webgl-utils.js"></script>
<script type="text/javascript" src="../Common/initShaders.js"></script>
<script type="text/javascript" src="../Common/MV.js"></script>
<script type="text/javascript" src="gasket5.js"></script>
</head>

<body>
<div>
recursive steps  0 <input id="slider" type="range"
 min="0" max="6" step="1" value="0" />
 6
</div>
<canvas id="gl-canvas" width="512" height="512">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
module Cloudpassage

  # Groups
  class Groups < Base
    include Collection
    def singleton_class
      Group
    end
  end

  class Group < Single
    def servers
      Servers.new(@token, @base_resource['servers'])
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.Net.Mail;
using System.Net.Mime;
using System.ComponentModel;

using PI.Pimail.Models;

namespace PI.Pimail
{
    /// <markdown>
    /// #PI.Pimail.Mail
    /// File: Mail.cs
    /// </markdown>
    /// <summary>
    /// Default Mail Class using the IMail interface
    /// </summary>
    public class Mail : IMail
    {

        #region Properties

        /// <markdown>
        /// ###public string TagStart
        /// </markdown>
        /// <summary>
        /// The start tag used as a placeholder
        /// </summary>
        public string TagStart { get; set; }

        /// <markdown>
        /// ###public string TagEnd
        /// </markdown>
        /// <summary>
        /// The end tag used as a placeholder
        /// </summary>
        public string TagEnd { get; set; }

        /// <markdown>
        /// ###public string FileRoot
        /// </markdown>
        /// <summary>
        /// The root folder for any file attachments
        /// </summary>
        public string FileRoot { get; set; }

        /// <markdown>
        /// ###private Email m_LastSentEmail
        /// </markdown>
        /// <summary>
        /// Internally stores a reference to the last email sent via the object
        /// </summary>
        private Email m_LastSentEmail = null;

        /// <markdown>
        /// ###public Email LastSentEmail
        /// </markdown>
        /// <summary>
        /// Returns the last email sent via the object, get only
        /// </summary>
        public Email LastSentEmail {
            get { return m_LastSentEmail; }
        }

        #endregion

        #region Constructors

        /// <markdown>
        /// ###public Mail(string fileRoot)
        /// </markdown>
        /// <summary>
        /// Default empty constructor with as used in live requests
        /// </summary>
        public Mail()
        {
            FileRoot = "";
            TagStart = "[";
            TagEnd = "]";
        }

        /// <markdown>
        /// ###public Mail(string fileRoot)
        /// </markdown>
        /// <summary>
        /// Constructor with a file root set on creation, to allow for context for testing
        /// </summary>
        /// <param name="fileRoot">The fileRoot as a string</param>
        public Mail(string fileRoot)
        {
            FileRoot = fileRoot;
            TagStart = "[";
            TagEnd = "]";
        }

        #endregion

        #region Methods: Hash Table

        private Hashtable m_ht = new Hashtable();

        /// <markdown>
        /// ###public void Add(object key, object value)
        /// </markdown>
        /// <summary>
        /// Adds a key and it's value to the Hash Table
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        public void Add(object key, object value)
        {
            m_ht.Add(key, value);
        }

        /// <markdown>
        /// ###public void Remove(object key)
        /// </markdown>
        /// <summary>
        /// Removes a key pair from the hash table
        /// </summary>
        /// <param name="key">Key to remove</param>
        public void Remove(object key)
        {
            m_ht.Remove(key);
        }

        /// <markdown>
        /// ###public void Clear()
        /// </markdown>
        /// <summary>
        /// Clears the hash table
        /// </summary>
        public void Clear()
        {
            m_ht.Clear();
        }

        /// <markdown>
        /// ###public void AddObject(object itemToAdd, string prefix = "")
        /// </markdown>
        /// <summary>
        /// Adds in bulk object properties to an email.
        /// The prefix should be added to the email parameters
        /// in the xml email body
        /// e.g. [PRIZE_DISPLAYNAME] where prefix is "PRIZE_"
        /// </summary>
        /// <param name="itemToAdd"></param>
        /// <param name="prefix">The parameters are prefixed with this to avoid duplicate addding of values such as id</param>
        public void AddObject(object itemToAdd, string prefix = "")
        {
            Type t = itemToAdd.GetType();
            foreach (PropertyInfo field in t.GetProperties())
            {
                var val = field.GetValue(itemToAdd, null);
                if (field.PropertyType.IsValueType || field.PropertyType == typeof(string))
                {
                    Add(prefix + field.Name.ToUpper(), val);
                }
                else if (val == null)
                {
                    Add(prefix + field.Name.ToUpper(), "");
                }
                else
                {
                    if (IsIEnumerable(val.GetType())) Add(prefix + field.Name.ToUpper(), val);
                }
            }
        }

        /// <markdown>
        /// ###private bool IsIEnumerable(Type someType)
        /// </markdown>
        /// <summary>
        /// Checks if a type is IEnumerable
        /// </summary>
        /// <param name="someType">The type to check for IEnumerable</param>
        /// <returns>true if the object is IEnumerable else returns false even on Exception</returns>
        private bool IsIEnumerable(Type someType)
        {
            try
            {
                if (someType.IsValueType || someType == typeof(string)) return false;

                Type[] listInterfaces = someType.GetInterfaces();
                foreach (Type t in listInterfaces)
                {
                    try
                    {
                        if (t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) return true;
                    }
                    catch { }
                    try
                    {
                        if (t == typeof(IEnumerable<>)) return true;
                    }
                    catch { }
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        #region Methods: Build

        /// <markdown>
        /// ###public MailMessage BuildMailMessage(Email email)
        /// </markdown>
        /// <summary>
        /// Builds a mail message from the email object sent with the hash table values replaced
        /// </summary>
        /// <param name="email">The email to create the mail message from</param>
        /// <returns>New MailMessage</returns>
        public MailMessage BuildMailMessage(Email email)
        {
            try
            {
                //create a clone of this object
                Email em = new Email()
                {
                    Name = email.Name,
                    To = ReplaceDynamicText(email.To),
                    Subject = ReplaceDynamicText(email.Subject),
                    BodyHtml = ReplaceDynamicText(email.BodyHtml),
                    BodyPlain = ReplaceDynamicText(email.BodyPlain),
                    IsBodyHtml = email.IsBodyHtml,
                    From = ReplaceDynamicText(email.From),
                    FromDisplay = ReplaceDynamicText(email.FromDisplay),
                    Cc = ReplaceDynamicText(email.Cc),
                    Bcc = ReplaceDynamicText(email.Bcc),
                    FilesToAttach = email.FilesToAttach,
                    ContentEncoding = email.ContentEncoding,
                    HeaderEncoding = email.HeaderEncoding,
                    AdditionalHeaders = email.AdditionalHeaders,
                    Priority = email.Priority,
                    ReplyTo = ReplaceDynamicText(email.ReplyTo)
                };

                // Create email message with default email address
                MailMessage mail = new MailMessage(em.From, em.From);

                // Set Email From
                mail.From = (!String.IsNullOrEmpty(em.FromDisplay)) ? new MailAddress(em.From, em.FromDisplay) : new MailAddress(em.From);

                // Clear and set Email To
                mail.To.Clear();
                SetAddresses(mail.To, em.To);

                // Check for and set Carbon Copy recipients
                if (!String.IsNullOrEmpty(em.Cc)) SetAddresses(mail.CC, em.Cc);

                // Check for and set Blind Carbon Copy recipients
                if (!String.IsNullOrEmpty(em.Bcc)) SetAddresses(mail.Bcc, em.Bcc);

                // Set Subject
                mail.Subject = em.Subject;

                // Check if plain text version specified
                if (em.IsBodyHtml && !String.IsNullOrEmpty(em.BodyPlain))
                {
                    // PLAIN TEXT VERSION
                    AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(em.BodyPlain, null, MediaTypeNames.Text.Plain);
                    mail.AlternateViews.Add(plainTextView);
                }

                // HTML TEXT VERSION
                mail.Body = (em.IsBodyHtml) ? em.BodyHtml : em.BodyPlain;
                mail.BodyEncoding = Encoding.GetEncoding(em.ContentEncoding);
                mail.IsBodyHtml = em.IsBodyHtml;

                if (em.IsBodyHtml && !String.IsNullOrEmpty(em.BodyHtml))
                {
                    // HTML VERSION
                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(em.BodyHtml, null, MediaTypeNames.Text.Html);
                    mail.AlternateViews.Add(htmlView);
                }

                mail.HeadersEncoding = Encoding.GetEncoding(em.HeaderEncoding);
                //if (!String.IsNullOrEmpty(em.AdditionalHeaders)) mail.Headers

                if (em.FilesToAttach != null) {
                    // Attachment
                    foreach (string file in em.FilesToAttach)
                    {
                        string path = FileRoot + file;
                        // Check if file exists
                        if (File.Exists(path))
                        {
                            // Attach file to message
                            Attachment messageAttachment = new Attachment(path);
                            mail.Attachments.Add(messageAttachment);
                        }
                    }
                }

                return mail;
            }
            catch
            {
                throw;
            }
        }

        /// <markdown>
        /// ###private void SetAddresses(MailAddressCollection mac, string addresses)
        /// </markdown>
        /// <summary>
        /// Sets email address collection from semi-colon seperated address string
        /// </summary>
        /// <param name="mac">Email Address Collection</param>
        /// <param name="addresses">Semi-colon seperated Email Addresses</param>
        private void SetAddresses(MailAddressCollection mac, string addresses)
        {
            try
            {
                foreach (string add in addresses.Split(';'))
                {
                    if (!add.StartsWith("[") && !add.EndsWith("]")) mac.Add(new MailAddress(add));
                }
            }
            catch { }
        }

        #endregion

        #region Methods: Merging

        /// <markdown>
        /// ###private string ReplaceDynamicText(string t, Hashtable h = null)
        /// </markdown>
        /// <summary>
        /// Replaces text based on a hash table
        /// </summary>
        /// <param name="t">String</param>
        /// <param name="h">Hash Table</param>
        /// <returns>String</returns>
        private string ReplaceDynamicText(string t, Hashtable h = null)
        {
            if (String.IsNullOrEmpty(t)) return t;
            if (h == null) h = m_ht;
            foreach (object k in h.Keys)
            {
                if (h[k] != null && IsIEnumerable(h[k].GetType()))
                {
                    string start = TagStart + k.ToString().ToUpper() + "_START" + TagEnd;
                    string end = TagStart + k.ToString().ToUpper() + "_END" + TagEnd;
                    //get template between key and _START and _END
                    int s = t.IndexOf(start, 0);
                    int e = t.IndexOf(end, 0);
                    if (s > -1 && e > s)
                    {
                        string template = t.Substring(s, e - s);
                        string str = "";
                        IEnumerable enumerable = (h[k] as IEnumerable);
                        foreach (var item in enumerable)
                        {
                            //add new line to the template
                            str += template;
                            //replace item
                            str = ReplaceDynamicText(str, item);
                        }
                        //replace entire template
                        t = t.Replace(template, str).Replace(start, "").Replace(end, "");
                    }
                } else {
                    var val = (h[k] != null) ? h[k].ToString() : "";
                    t = t.Replace(TagStart + k.ToString().ToUpper() + TagEnd, val);
                }
            }
            return t;
        }

        /// <markdown>
        /// ###private string ReplaceDynamicText(string t, object o)
        /// </markdown>
        /// <summary>
        /// Replaces text based on the object sent
        /// </summary>
        /// <param name="t">Text</param>
        /// <param name="o">Object</param>
        /// <returns>String</returns>
        private string ReplaceDynamicText(string t, object o)
        {
            Type tp = o.GetType();
            FieldInfo[] fs = tp.GetFields(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < fs.Length; i++)
            {
                var prp = fs[i].GetValue(o);
                var val = (prp != null) ? prp.ToString() : "";
                t = t.Replace(TagStart + fs[i].Name.ToUpper() + TagEnd, val);
            }
            //for generics
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(o);
            foreach (PropertyDescriptor prop in props)
            {
                var prp = prop.GetValue(o);
                var val = (prp != null) ? prp.ToString() : "";
                t = t.Replace(TagStart + prop.Name.ToUpper() + TagEnd, val);
            }
            return t;
        }

        #endregion
    }
}


text:
/* These styles assume you are using ul and li */
.dropit {
    list-style: none;
	padding: 0;
	margin: 0;
}
.dropit .dropit-trigger { position: relative; }
.dropit .dropit-submenu {
    position: absolute;
    top: 100%;
    left: 0; /* dropdown left or right */
    z-index: 1000;
    display: none;
    min-width: 150px;
    list-style: none;
	padding: 0;
	margin: 0;
}
.dropit .dropit-open .dropit-submenu { display: block; }

.menu {
    width: auto !important;
    display: inline-block;
    font-weight: 100;
    margin: 0 2px !important;
}

.menu a {
    text-decoration: none;
}

.menu .selection {
    background-color: #EEE;
    text-align: center;
    color: #262626;
    display: inline-block;
    padding: 3px 6px 4px 6px;
}

.menu ul { display: none; } /* Hide before plugin loads */
.menu ul.dropit-submenu {
    background-color: #CCC;
    border-top: 1px dashed #262626;
    color: #262626;
    width: 120px;
}

.menu ul.dropit-submenu li {
    display: block;
    line-height: 25px;
    color: #262626;
    padding: 0 18px;
    cursor: pointer;
}

.menu ul.dropit-submenu li:hover {
    background: #f00;
    color: #fff;
    text-decoration: none;
}

.arrow-down {
    width: 0;
    height: 0;
    border-left: 3px solid transparent;
    border-right: 3px solid transparent;
    border-top: 5px solid #262626;
    display: inline-block;
    float: right;
    margin-top: 8px;
    margin-left: 8px;
}


text:
#import "EC2CancelSpotInstanceRequestsResponse.h"

@implementation EC2CancelSpotInstanceRequestsResponse

@synthesize cancelledSpotInstanceRequests;

-(id)init
{
    if (self = [super init]) {
        cancelledSpotInstanceRequests = [[NSMutableArray alloc] initWithCapacity:1];
    }

    return self;
}

-(void)setException:(AmazonServiceException *)theException
{
    AmazonServiceException *newException = nil;

    if (newException != nil) {
        [newException setPropertiesWithException:theException];
        [exception release];
        exception = newException;
    }
    else {
        [exception release];
        exception = [theException retain];
    }
}

-(EC2CancelledSpotInstanceRequest *)cancelledSpotInstanceRequestsObjectAtIndex:(int)index
{
    return (EC2CancelledSpotInstanceRequest *)[cancelledSpotInstanceRequests objectAtIndex:index];
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"CancelledSpotInstanceRequests: %@,", cancelledSpotInstanceRequests] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [cancelledSpotInstanceRequests release];

    [super dealloc];
}

@end


text:
The goal of Wade in the Water is to compose an image of the impact of the movement for Black lives has since the unrest in Ferguson in the summer and fall of 2014, from snapshots provided by a range of Black interviewees. When this all began, it seemed to some that it would blow over by the next news cycle. Now, some are comparing it to the Civil Rights Movement of the 50s and 60s.

# Stack

This project is forked from `foundation-jekyll`, a project by Aaron White.


text:
require "edition"
require 'gds_api/panopticon'

class Edition
  include Admin::BaseHelper

  class ResurrectionError < RuntimeError
  end

  scope :internal_search, lambda { |term|
    regex = Regexp.new(Regexp.escape(term), true)  # case-insensitive
    any_of({title: regex}, {slug: regex}, {overview: regex},
           {alternative_title: regex}, {licence_identifier: regex})
  }

  alias_method :was_published_without_indexing, :was_published
  def was_published
    was_published_without_indexing
    register_with_panopticon
  end

  def fact_check_skipped?
    actions.any? and actions.last.request_type == 'skip_fact_check'
  end

  def register_with_panopticon
    artefact = Artefact.find(self.panopticon_id)
    if artefact.state == "archived"
      raise ResurrectionError, "Cannot register archived artefact '#{artefact.slug}'"
    end

    format_as_kind = self.format.underscore
    registerer = GdsApi::Panopticon::Registerer.new(owning_app: "publisher", rendering_app: "frontend", kind: format_as_kind)
    details = RegisterableEdition.new(self)
    registerer.register(details)
  end
end


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W31069_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Shawn Ghani
From: Shawn Ghani Sent: Tuesday, February 24, 2015 8:22 AM To- 'katiel@co.wi|liams.nd.us'
Subject: Whiting Oil 81 Gas Corporation - Request for Physical Address

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Good morning Katie, Please provide Physical Address for the attached new location.
Thank vou verv much in advance.

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans23.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Williams County Physicahdsx

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sincerely,

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Shawn Ghani Regulatory Compliance Specialist I"
Whiting Petroleum Corporation and its wholly owned subsldlary
Whiting Oil and Gas Corporation 1700 Broadway, Suite 2300 Denver, CO 80290
Direct (303) 802-8338
shawn.ghani@whiting.com www.whiting.com

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
CLI for easier [PrestaShop](http://www.prestashop.com/en/) development. Actually it's just for the lazy people.

I always use Rakefiles and Makefiles for lots of tasks. With this gem you can use these tasks without having to create any *akefiles. For more infos about how and why see: [Introducing Shop](http://romainberger.com/2013/09/29/introducing-shop/).

Shop has been developed to work with PrestaShop 1.5 and 1.4 (support for 1.6 will be added once it's realeased).

## Installation

    gem install shop

## Usage

### New project

Creates a new Prestashop project with:

    shop new <directory> [version]

    # example:
    shop new
    # Download the framework (stable version) in the current directory

    shop new new-store
    # Download the framework in a new directory `new-store`

Download the latest stable version (1.5) of PrestaShop in the current directory or in a subdirectory if you provide the name as argument.

Even if the 1.6 version is not out yet you can create new projects with this version by passing the version as an argument:

    shop new 1.6
    # Create a new project in the current directory with Prestashop 1.6

    shop new new-store 1.6
    # Create a new project in a new directory `new-store` with the version 1.6

**Note**: Shop can work with an existing PrestaShop project, all you need is to initialize the Shop project (see [Initialization](https://github.com/romainberger/shop/#initialization) below)

### Installation

Since 1.5.4 [PrestaShop provides a CLI](http://doc.prestashop.com/display/PS15/Installing+PrestaShop+using+the+command+line) to install your PrestaShop. You can try to remember every arguments, or just use the Shop task and stay relatively sane (no offense to the PrestaShop developers but... come on). You will need to create the database before running this task.

    # php install/cli.php --name=Romain --lol=whyamitypingallthis
    # nope
    shop install

**Note**: the install task actually runs the PrestaShop PHP CLI. It just makes you happier with a nice prompt.

### Initialization

For some tasks, Shop will need to know the name of the theme you're using. To do that you need to init the project with:

    shop init <theme-name>

    # example:
    shop init my-theme

### Overrides

Creates overrides files for controllers and classes.

    shop override <controller|class> <name> [admin]

    # examples:

    # generate an override for the Product controller
    shop override controller Product

    # by default the controller will be placed in override/controllers/admin. To create an override in
    # override/controllers/admin add the `admin` argument:
    shop override controller AdminProducts admin

    # generate an override for the Product class
    shop override class Product

### New Pages

You can generate new pages for PrestaShop easily with the `controller` command. This will create the controller, template, CSS and JS files you need to create a new page.

    shop controller <page-name>

    # example:
    shop controller CustomPage

### Modules

**The modules related tasks will need the Shop project to be [initialized](https://github.com/romainberger/shop)**

Creates a new module (with simple module boilerplate):

    shop module <name>

    # example:
    shop module dinozaure

Creates a module template:

    shop module template <module-name> <hook-name>

    # example:
    shop module template blockcategories blockcategories

Creates a module css file in your theme:

    shop module css <module-name>

    # example:
    shop module css blockcategories

### Cache

Cleans the css and js caches.

    shop clean [cache]
    # cleans the css and js caches

When you create a new override for a controller or a class, the class index needs to be rewritten. You can call this task

    shop clean class
    # clean the class index - automatically done when generating a new controller or class

By default the `clean` task will clean the cache so you can just use `shop clean`.

**Note**: The class index is automatically regenerated when you create an override with Shop. You probably won't need to run this command.

### Jshint

Run jshint on the theme's files.

    shop jshint

To run jshint on the theme's files and the modules' files, run it with the `modules` argument:

    shop jshint modules

To run jshint on **every** files run it with the `hard` argument (prepare yourself for a crapload of errors):

    shop jshint hard

### Makefile

Okay I kinda lied. I still use a Makefile, but only for production servers, as they rarely run gems and I don't necessarily want to install a tool for a limited use (Shop is primarily built for development purpose). But some of these tasks can be usefull on production servers. Shop can generate a Makefile file that will allow you to run some tasks.

**The Makefile task will need the Shop project to be [initialized](https://github.com/romainberger/shop)**

If you already use a Makefile, the tasks will be added to it. If you don't, it will create a Makefile.

    shop makefile

You can then use these tasks. Their effect are similar to the Shop tasks.

    make clean-cache

    make clean-class

### Help

You can get a list of the available commands with the help:

    shop help

## Configuration

You can use a configuration file to automate some values in the templates files created (modules and for the installation of PrestaShop).
You can edit this file with the command

    shop edit

It will open the config file in your `$EDITOR`. It's YAML so it shouldn't be scary.

## Custom templates

Some tasks generates files, using templates located in [/templates](https://github.com/romainberger/shop/tree/master/templates). You can override these files to use custom ones. See the [template readme for more infos](https://github.com/romainberger/shop/tree/master/templates).

## Autocompletion

To enable autocompletion with Shop, [see the docs.](https://github.com/romainberger/shop/tree/master/completion)

## Compatibility

Shop has been developed and tested on osx. It may not work on platforms other than *nix, particularly the `new` command that uses the unix `unzip` command. I plan on working on rewriting this part with only Ruby so it could work everywhere. I'm not going to try it on Windows so feel free to open issues (or even better, contribute) if you notice something not working as expected.

## Who

By [Romain Berger](http://romainberger.com).
Ping me at [@romain__berger](http://twitter.com/romain__berger) if you're having issues or create an issue.

If you become billionaire with a shop made with the help of Shop you can be cool and buy me a beer.


text:
function error=feature_index_template_Skript(features);

numFeat=size(features)

for i=1:numFeat(2)
    error=features_precompute_Skript(features(i));
    create_DB_info;
    error=DB_index_precompute_Skript(features(i));
    error=motionTemplatePrecomputeBatch_skript(features(i));
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tarantula
{
    public partial class FrmAbout : Form
    {
        public FrmAbout()
        {
            InitializeComponent();
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


text:
package com.versionone.integration.ciCommon.tests;

import com.versionone.integration.ciCommon.V1Worker;
import com.versionone.integration.teamcity.FileConfig;
import com.versionone.integration.teamcity.V1Connector;
import com.versionone.om.PrimaryWorkitem;
import com.versionone.om.Project;
import com.versionone.om.Story;
import com.versionone.om.Task;
import com.versionone.om.V1Instance;
import jetbrains.buildServer.vcs.SVcsModification;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class V1WorkerTester {
    private Mockery mockery = new Mockery() {
        {
            setImposteriser(ClassImposteriser.INSTANCE);
        }
    };

    @After
    public void deleteCfgFile() {
        File file = new File(".", FileConfig.CONFIG_FILENAME);
        file.delete();
    }

    @Test
    public void testGetModificationDescription() {
        final String userName1 = "user name 1";
        final String userName2 = "user name 2";
        final String desc1 = "description 1";
        final String desc2 = "description 2";

        final SVcsModification modification1 = mockery.mock(SVcsModification.class, "changelist 1");
        final SVcsModification modification2 = mockery.mock(SVcsModification.class, "changelist 2");
        List<SVcsModification> modifications = Arrays.asList(modification1, modification2);

        mockery.checking(new Expectations() {
            {
                allowing(modification1).getDescription();
                will(returnValue(desc1));
                allowing(modification2).getDescription();
                will(returnValue(desc2));
                allowing(modification1).getUserName();
                will(returnValue(userName1));
                allowing(modification2).getUserName();
                will(returnValue(userName2));
            }
        });

        final String result = V1Worker.getModificationDescription(modifications);

        Assert.assertTrue(result.contains(userName1));
        Assert.assertTrue(result.contains(userName2));
        Assert.assertTrue(result.contains(desc1));
        Assert.assertTrue(result.contains(desc2));
    }

    @Test
    @Ignore(value = "Integration test")
    public void testResolveReference() {
        final V1Connector connector = new V1Connector();
        final FileConfig cfg = V1ConfigTester.getValidConfig();
        connector.setConnectionSettings(cfg);
        Assert.assertTrue(connector.isConnectionValid());

        final String storyName = "TeamCity integ test story";
        final String taskName = "TeamCity integ test task";
        final V1Instance v1Instace = connector.getV1Instance();
        final Project project = v1Instace.get().projectByID("Scope:0");

        final Story story = v1Instace.create().story(storyName, project);
        final Task task = story.createTask(taskName);

        List<PrimaryWorkitem> workItems = connector.getPrimaryWorkitemsByReference(story.getDisplayID());

        Assert.assertEquals(1, workItems.size());
        Assert.assertEquals(storyName, workItems.iterator().next().getName());

        workItems = connector.getPrimaryWorkitemsByReference(task.getDisplayID());

        Assert.assertEquals(1, workItems.size());
        Assert.assertEquals(storyName, workItems.iterator().next().getName());

        story.delete();
    }
}


text:
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * $Id: RealExpr.java,v 1.2 2005/08/16 22:30:35 jeffsuttor Exp $
 */

package com.sun.org.apache.xalan.internal.xsltc.compiler;

import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;

/**
 * @author Jacek Ambroziak
 * @author Santiago Pericas-Geertsen
 */
final class RealExpr extends Expression {
    private double _value;

    public RealExpr(double value) {
        _value = value;
    }

    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
        return _type = Type.Real;
    }

    public String toString() {
        return "real-expr(" + _value + ')';
    }

    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
        ConstantPoolGen cpg = classGen.getConstantPool();
        InstructionList il = methodGen.getInstructionList();
        il.append(new PUSH(cpg, _value));
    }
}


text:
//
//  SKConversionProgressController.h
// Skim
//
//  Created by Adam Maxwell on 12/6/06.

#import <Cocoa/Cocoa.h>

@interface SKConversionProgressController : NSWindowController {
    NSButton *cancelButton;
    NSProgressIndicator *progressBar;
    NSTextField *textField;
    NSString *fileType;
    CGPSConverterRef converter;
    volatile int32_t convertingPS;
    volatile int32_t cancelled;
}

@property (nonatomic, retain) IBOutlet NSButton *cancelButton;
@property (nonatomic, retain) IBOutlet NSProgressIndicator *progressBar;
@property (nonatomic, retain) IBOutlet NSTextField *textField;

+ (NSData *)PDFDataWithPostScriptData:(NSData *)psData error:(NSError **)outError;
+ (NSData *)PDFDataWithDVIFile:(NSString *)dviFile error:(NSError **)outError;
+ (NSData *)PDFDataWithXDVFile:(NSString *)xdvFile error:(NSError **)outError;

- (IBAction)cancel:(id)sender;
- (IBAction)close:(id)sender;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:id="@+id/moduleIcon"
        android:adjustViewBounds="true"
        >
    </ImageView>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:id="@+id/moduleName"
        android:text="oa"
        ></TextView>
</RelativeLayout>


text:
var config = module.exports;

config.environment = "development";

// when doing dev on real ios device, switch this line to your current
// ip address. Then login to https://console.cloud.google.com/apis/credentials?project=celtic-defender-718
// using "bunkerjschat" login, go to "OAuth 2.0 client IDs", then "Development" add "http://192.168.1.27.xip.io:9002"
// to "Authorized JavaScript origins" and "http://192.168.1.27.xip.io:9002/auth/googleReturn" to Authorized redirect URIs

// config.url = "http://192.168.1.27.xip.io:9002";

config.url = "http://localhost:9002";

config.db = {
	host: "localhost",
	name: "bunker",
	session: "bunker_sessions",
	port: "27017"
};

config.express = {
	hostName: "localhost",
	port: 9002,
	ip: "127.0.0.1"
};

config.google = {
	clientID: "744915257573-ri8suktjsu5s1b3jddkacm6k0a45vi02.apps.googleusercontent.com",
	clientSecret: "PvaKpOF_Uh9MrJ-506YoOO9r",
	cse_id: "018153030878338156363:umvujbgdj6s",
	cse_key: "AIzaSyADOhR5rYXCoBHR5fWRw0LB5r6Myp6atME"
};

config.bingApiKey = "WOz19RNOpvm7kP+Xwc1zhz23Oemq9Jhdcs5+xvbjxKY";

config.consoleLogLevel = "debug";
config.buildSassAtRuntime = true;
config.useJavascriptBundle = false;

config.showServerErrors = true;
config.useRedis = false;


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lactarius salicis-herbaceae var. salis-herbaceae Kühner

### Remarks
null


text:
package udp

import (
	"encoding/base64"
	"net"
	"sync"
	"time"

	"github.com/fatedier/frp/models/msg"

	"github.com/fatedier/golib/errors"
	"github.com/fatedier/golib/pool"
)

func NewUDPPacket(buf []byte, laddr, raddr *net.UDPAddr) *msg.UDPPacket {
	return &msg.UDPPacket{
		Content:    base64.StdEncoding.EncodeToString(buf),
		LocalAddr:  laddr,
		RemoteAddr: raddr,
	}
}

func GetContent(m *msg.UDPPacket) (buf []byte, err error) {
	buf, err = base64.StdEncoding.DecodeString(m.Content)
	return
}

func ForwardUserConn(udpConn *net.UDPConn, readCh <-chan *msg.UDPPacket, sendCh chan<- *msg.UDPPacket, bufSize int) {
	// read
	go func() {
		for udpMsg := range readCh {
			buf, err := GetContent(udpMsg)
			if err != nil {
				continue
			}
			udpConn.WriteToUDP(buf, udpMsg.RemoteAddr)
		}
	}()

	// write
	buf := pool.GetBuf(bufSize)
	defer pool.PutBuf(buf)
	for {
		n, remoteAddr, err := udpConn.ReadFromUDP(buf)
		if err != nil {
			return
		}
		// buf[:n] will be encoded to string, so the bytes can be reused
		udpMsg := NewUDPPacket(buf[:n], nil, remoteAddr)

		select {
		case sendCh <- udpMsg:
		default:
		}
	}
}

func Forwarder(dstAddr *net.UDPAddr, readCh <-chan *msg.UDPPacket, sendCh chan<- msg.Message, bufSize int) {
	var (
		mu sync.RWMutex
	)
	udpConnMap := make(map[string]*net.UDPConn)

	// read from dstAddr and write to sendCh
	writerFn := func(raddr *net.UDPAddr, udpConn *net.UDPConn) {
		addr := raddr.String()
		defer func() {
			mu.Lock()
			delete(udpConnMap, addr)
			mu.Unlock()
			udpConn.Close()
		}()

		buf := pool.GetBuf(bufSize)
		for {
			udpConn.SetReadDeadline(time.Now().Add(30 * time.Second))
			n, _, err := udpConn.ReadFromUDP(buf)
			if err != nil {
				return
			}

			udpMsg := NewUDPPacket(buf[:n], nil, raddr)
			if err = errors.PanicToError(func() {
				select {
				case sendCh <- udpMsg:
				default:
				}
			}); err != nil {
				return
			}
		}
	}

	// read from readCh
	go func() {
		for udpMsg := range readCh {
			buf, err := GetContent(udpMsg)
			if err != nil {
				continue
			}
			mu.Lock()
			udpConn, ok := udpConnMap[udpMsg.RemoteAddr.String()]
			if !ok {
				udpConn, err = net.DialUDP("udp", nil, dstAddr)
				if err != nil {
					mu.Unlock()
					continue
				}
				udpConnMap[udpMsg.RemoteAddr.String()] = udpConn
			}
			mu.Unlock()

			_, err = udpConn.Write(buf)
			if err != nil {
				udpConn.Close()
			}

			if !ok {
				go writerFn(udpMsg.RemoteAddr, udpConn)
			}
		}
	}()
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Microsoft.VisualBasic;

namespace CS410Project
{
    public partial class MainWindow : Form
    {
        private static readonly log4net.ILog Log = LogHelper.GetLogger();
        public Loginout loginManager = new Loginout();
        public RemoteDirectory remoteDirectory = new RemoteDirectory();
        public LocalDirectory localDirectory = new LocalDirectory();
        public Client client;
        string[] files;
        getFile temp;
        bool hidden = false; //boolean value whether or not the owner window is hidden or not

        public MainWindow()
        {
            InitializeComponent();
            populateLocalDirectoryBox(localDirectory.getDirectoryStructure());
            SettingsController.initializeSettings(this);
        }

        private void MainWindow_Exit(object sender, FormClosingEventArgs e)
        {
            if (hidden)
            {
                Owner.Show();
                hidden = !hidden;
            }
            Close();
        }

        private void Timeout_Event(object sender, EventArgs e)
        {
            loginManager.Timeout();
            MessageBox.Show("Automatic timeout has triggered", "Timed out", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void ParentButton_Click(object sender, EventArgs e)
        {
            if (loginManager.LoggedIn)
            {
                remoteDirectory.changeToParentDirectory(client);
                populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
            }
        }

        private void LocalParentDirectory_Click(object sender, EventArgs e)
        {
            localDirectory.changeToParentDirectory();
            populateLocalDirectoryBox(localDirectory.getDirectoryStructure());
        }

        private void LocalDirectory_DoubleClick(object sender, EventArgs e)
        {
            if (LocalDirectory.SelectedItem != null)
            {
                string index = LocalDirectory.SelectedItem.ToString();
                if (!localDirectory.changeToDirectory(index))
                {
                    //maybe add uploading here I don't know
                }
                populateLocalDirectoryBox(localDirectory.getDirectoryStructure());
            }
        }
        private void RemoteDirectory_DoubleClick(object sender, EventArgs e)
        {
            if (loginManager.LoggedIn)
            {
                if (RemoteDirectory.SelectedItem != null)
                {
                    string index = RemoteDirectory.SelectedItem.ToString();
                    if (!remoteDirectory.changeToDirectory(client, index))
                    {
                        //It's a file, not a directory, so just download it
                        Console.WriteLine();
                        temp = new getFile(RemoteDirectory.SelectedItem.ToString(), "");
                        if (!backWorkGetProg.IsBusy)
                        {
                            backWorkGetProg.RunWorkerAsync();
                        }
                        else
                        {
                            MessageBox.Show("An upload or download is currently in progress");
                        }
                    }
                    populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
                }
            }
        }
        //This method populates the listbox to contain the current working directory of the FTP server
        private void populateRemoteDirectoryBox(List<string> input)
        {
            //Wipe out the box before adding items
            RemoteDirectory.Items.Clear();
            //Add items one by one from the directory's structure
            for (int i = 0; i < input.Count; i++)
            {
                RemoteDirectory.Items.Add(input[i]);
            }
        }

        //This method populates the listbox to contain the current working directory of the FTP server
        private void populateLocalDirectoryBox(List<string> input)
        {
            //Wipe out the box before adding items
            LocalDirectory.Items.Clear();
            //Add items one by one from the directory's structure
            for (int i = 0; i < input.Count; i++)
            {
                LocalDirectory.Items.Add(input[i]);
            }
        }

        private void getFile_Click(object sender, EventArgs e)
        {
            if (loginManager.LoggedIn)
            {
                if (RemoteDirectory.SelectedItem != null)
                {
                    //this implementation assumes a single selected item; change to list later
                    //in the case of multiple selected items.
                    String[] Selected = new String[RemoteDirectory.SelectedItems.Count];
                    RemoteDirectory.SelectedItems.CopyTo(Selected, 0);
                    temp = new getFile(Selected, "");
                    if (!backWorkGetProg.IsBusy)
                    {
                        backWorkGetProg.RunWorkerAsync();
                    }
                    else
                    {
                        MessageBox.Show("An upload or download is currently in progress");
                    }
                }
            }
        }

        private void PutFile_Click(object sender, EventArgs e)
        {
            if (loginManager.LoggedIn)
            {
                OpenFileDialog opFilDlg = new OpenFileDialog();
                opFilDlg.Multiselect = true;
                if (opFilDlg.ShowDialog() == DialogResult.OK)
                {
                    files = opFilDlg.FileNames;
                    if (!backWorkProgBar.IsBusy)
                    {
                        backWorkProgBar.RunWorkerAsync();
                    }
                    else
                    {
                        MessageBox.Show("An upload or download is currently in progress");
                    }
                    remoteDirectory.refreshDirectory(client);
                    populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
                }
            }
        }

        private void CreateRemoteDir_Click(object sender, EventArgs e)
        {
            string value = "Enter directory name";
            if (InputBox("New directory", "New directory name:", ref value) == DialogResult.OK)
            {
                string remoteDirText = value;

                if (string.IsNullOrWhiteSpace(remoteDirText)) { return; }

                if (client.createRemoteDir(remoteDirText))
                {
                    remoteDirectory.refreshDirectory(client);//refresh remote directory
                    populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());//refresh workingDirectory view
                }
                else
                    MessageBox.Show("Directory creation failed", "Error");
            }
        }

        private void DeleteFile_Click(object sender, EventArgs e)
        {
            if (RemoteDirectory.SelectedItem == null) { return; }

            if (client.deleteRemoteFile(RemoteDirectory.SelectedItem.ToString()))
            {
                remoteDirectory.refreshDirectory(client);
                populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());//refresh workingDirectory view
            }
            else if (client.deleteRemoteDir(RemoteDirectory.SelectedItem.ToString()))
            {
                remoteDirectory.refreshDirectory(client);
                populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
            }
            else
                MessageBox.Show("Delete failed", "Error");
        }

        //Remote Rename
        private void RenameFile_Click(object sender, EventArgs e)
        {
            if (RemoteDirectory.SelectedItem == null)
            {
                return;
            }
            else
            {
                string current = RemoteDirectory.SelectedItem.ToString();
                string value = "Enter new file name";

                if (InputBox("Rename File", "New file name:", ref value) == DialogResult.OK)
                {
                    if (string.IsNullOrWhiteSpace(value)) { return; }
                    try
                    {
                        client.renameRemoteFile(current, value);

                    }
                    catch (Exception d)
                    {
                        Console.WriteLine("The process failed: {0}", d.ToString());
                        MessageBox.Show("Rename error occured");
                        return;
                    }

                    MessageBox.Show("File renamed successfully");

                    remoteDirectory.refreshDirectory(client);//refresh remote directory
                    populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());//refresh workingDirectory view
                }
            }

        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            loginManager.EnableTimeoutTimer(Timeout_Event, 360);
            remoteDirectory = new RemoteDirectory();
            remoteDirectory.initializeDirectory(client);
            populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
        }

        //Toolbar for change Font
        private void changeFontToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult fontdialog = fontWindow.ShowDialog();
            if (fontdialog == DialogResult.OK)
            {
                Font font = fontWindow.Font;
                CS410Project.Properties.Settings.Default.SysFont = font;
                CS410Project.Properties.Settings.Default.Save();
                List<Control> allWindows = SettingsController.getAllControls(this);
                allWindows.ForEach(x => x.Font = font);
            }
        }

        private void changeColorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsForm settingsForm = new SettingsForm();
            settingsForm.ShowDialog(this);
        }

        public DialogResult InputBox(string title, string promptText, ref string value)

        {
            Form form = new Form();
            form.Font = CS410Project.Properties.Settings.Default.SysFont;
            form.BackColor = CS410Project.Properties.Settings.Default.BackgroundColor;
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            buttonOk.BackColor = CS410Project.Properties.Settings.Default.ButtonColor;
            Button buttonCancel = new Button();
            buttonCancel.BackColor = CS410Project.Properties.Settings.Default.ButtonColor;
            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;
            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }

        private void RemoteNewFile_Click(object sender, EventArgs e)
        {

            if (loginManager.LoggedIn)
            {

                string value = "Enter file name";
                if (InputBox("New file", "New file name:", ref value) == DialogResult.OK)
                {
                    using (File.Create(value)) { }
                    MessageBox.Show("File " + value + " created ");
                }
                client.putFile(value);
                remoteDirectory.refreshDirectory(client);
                populateRemoteDirectoryBox(remoteDirectory.getDirectoryStructure());
            }
        }

        private void CreateLocalDir_Click(object sender, EventArgs e)
        {
            string value = "Enter directory name";
            if (InputBox("New directory", "New directory name:", ref value) == DialogResult.OK)
            {
                string localDirText = value;

                if (string.IsNullOrWhiteSpace(localDirText)) { return; }

                if (localDirectory.createLocalDirectory(localDirText))
                {
                    localDirectory.refreshDirectory();
                    populateLocalDirectoryBox(localDirectory.getDirectoryStructure());//refresh workingDirectory view with addition of new directory
                }
                else
                    MessageBox.Show("A directory with that name already exists.", "Error");
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (string filePath in files)
            {
                backWorkProgBar.ReportProgress(0);
                client.putFile(filePath, backWorkProgBar);
            }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblStatus.Text = e.ProgressPercentage + "%";
            progressBar.Value = e.ProgressPercentage;
            progressBar.Update();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblStatus.Text = "Complete";
            backWorkProgBar.Dispose();
        }

        private void LocalSearchButton_Click(object sender, EventArgs e)
        {
            string inputSearch = LocalSearchBox.Text;
            localDirectory.searchLocalDirectory(inputSearch);
        }

        private void LocalRenameFileButton_Click(object sender, EventArgs e)
        {
            if (LocalDirectory.SelectedItem == null)
            {
                return;
            }
            else
            {
                string current = LocalDirectory.SelectedItem.ToString();
                string value = "Enter new file name";

                if (InputBox("Rename File", "New file name:", ref value) == DialogResult.OK)
                {
                    if (string.IsNullOrWhiteSpace(value)) { return; }
                    Exception returnValue;
                    returnValue = localDirectory.renameLocalFile(current, value);
                    if(returnValue == null) //success case with no exceptions
                    {
                        MessageBox.Show("File renamed successfully");
                    }
                    else //failure case with some exception
                    {
                        MessageBox.Show("Error: " + returnValue.Message);
                    }
                    localDirectory.refreshDirectory();
                    populateLocalDirectoryBox(localDirectory.getDirectoryStructure());//refresh workingDirectory view with renamed file.
                }
            }

        }

        private void backWorkGetProg_DoWork(object sender, DoWorkEventArgs e)
        {
            temp.saveFiles(client, backWorkGetProg);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This is a project for Portland State University CS410 Agile Software development. \nThis project was developed by:\nBen Lawrence\nChris Gatehouse\nJonathan Hasbun\nMiles Sanguinetti\nMohammed Inoue", "About", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void githubReadmeOpensWebBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://github.com/ChrisGatehouse/CS410");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (hidden)
            {
                Owner.Show();
                hidden = !hidden;
            }
            loginManager.Logout(client);
            Close();
        }

        private void RemoteSearchButton_Click(object sender, EventArgs e)
        {
            string inputSearch = RemoteSearchBox.Text;
            remoteDirectory.searchRemoteDirectory(client, inputSearch);
        }

        private void hideLogInWindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!hidden)
            {
                Owner.Hide();
                hidden = !hidden;
            }
            else
            {
                Owner.Show();
                hidden = !hidden;
            }
        }
    }
}


text:
import time
import logging
from random import randint

from grab.util.py3k_support import *

logger = logging.getLogger('grab.tools.control')

def sleep(lower_limit, upper_limit):
    """
    Sleep for random number of seconds in interval
    between `lower_limit` and `upper_limit`
    """

    # Doing this math calculations
    # to call randint function with integer arugments
    # There is no random function which accepts float arguments
    lower_limit_float = int(lower_limit * 1000)
    upper_limit_float = int(upper_limit * 1000)
    sleep_time = randint(lower_limit_float, upper_limit_float) / 1000.0
    logger.debug('Sleeping for %f seconds' % sleep_time)
    time.sleep(sleep_time)

def repeat(func, limit=3, args=None, kwargs=None,
           fatal_exceptions=(), valid_exceptions=()):
    """
    Return value of execution `func` function.

    In case of error try to execute `func` maximum `limit` times
    and then raise latest exception.

    Example::

        def download(url):
            return urllib.urlopen(url).read()

        data = repeat(download, 3, args=['http://google.com/'])

    """
    for try_count in xrange(1, limit + 1):
        try:
            res = func(*(args or ()), **(kwargs or {}))
        except Exception as ex:
            if isinstance(ex, fatal_exceptions):
                raise
            elif valid_exceptions and not isinstance(ex, valid_exceptions):
                raise
            else:
                logging.error('', exc_info=ex)
                if try_count >= limit:
                    logger.error('Too many errors while executing function %s' % func.__name__)
                    raise
        else:
            return res


text:
package com.gooddies.graphics;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 * @author dsavchenko
 */
public class InteractiveIcon implements Icon {

    private ImageIcon rollover = null;
    private ImageIcon defaultIcon = null;
    private ImageIcon pressed = null;
    private String path = null;

    /**
     * @param path path to the icon file(jpg, bmp, png...). If exists file
     * path_rollover.jpg(bmp, png...), class will load it as rollover
     * image(getRolloverIcon()). If exists file path_pressed.jpg(bmp, png...)
     * class will load it as pressed image(getPressedIcon()).
     */
    public InteractiveIcon(String path) {
        this.path = path;
        try {
            BufferedImage image = ImageIO.read(new File(path));
            defaultIcon = new ImageIcon(image);
        } catch (IIOException e) {
            try {
                defaultIcon = new ImageIcon(InteractiveIcon.class.getResource(path));
            } catch (Exception ex) {
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public InteractiveIcon(BufferedImage icon) {
        defaultIcon = new ImageIcon(icon);
    }

    public InteractiveIcon(ImageIcon icon) {
        defaultIcon = icon;
    }

    public Icon getDefaultIcon() {
        return defaultIcon;
    }

    public void clearRolloverPressedIcons(){
        rollover=null;
        pressed=null;
    }

    public Icon getRolloverIcon() {
        if (rollover == null) {
            String rolloverPath = getFileName(path) + "_rollover" + getFileExt(path);
            if (InteractiveIcon.class.getResource(rolloverPath) != null) {
                rollover = new ImageIcon(InteractiveIcon.class.getResource(rolloverPath));
            } else {
                rollover = createRolloverIcon(defaultIcon);
            }
        }

        return rollover;
    }

    public Icon getPressedIcon() {
        if (pressed == null) {
            String pressedPath = getFileName(path) + "_pressed" + getFileExt(path);
            if (InteractiveIcon.class.getResource(pressedPath) != null) {
                pressed = new ImageIcon(InteractiveIcon.class.getResource(pressedPath));
            } else {
                pressed = createPressedIcon(defaultIcon);
            }
        }
        return pressed;
    }

    private String getFileName(String path) {
        if (path == null) {
            return "";
        }
        int index = path.lastIndexOf('.');
        if (index > 0 && index <= path.length() - 2) {
            return path.substring(0, index);
        }
        return "";
    }

    private String getFileExt(String path) {
        if (path == null) {
            return "";
        }
        int index = path.lastIndexOf('.');
        if (index > 0 && index <= path.length() - 2) {
            return path.substring(index);
        }
        return "";
    }

    private ImageIcon mirrorHorizontal(ImageIcon icon) {
        BufferedImage image = convertImageToBufferedImage(icon);
        Graphics2D g2d = (Graphics2D) image.getGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        int[] buf = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        int w = image.getWidth();
        int h = image.getHeight();
        int centerX = w / 2;
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < centerX; x++) {
                int v = buf[x];
                buf[x] = buf[w - x];
                buf[w - x] = v;
            }
        }

        ImageIcon resultIcon = new ImageIcon(image);
        return resultIcon;
    }

    private ImageIcon mirrorVertical(ImageIcon icon) {
        BufferedImage image = convertImageToBufferedImage(icon);
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        int height=icon.getIconHeight();
        tx.translate(0, -height);
        AffineTransformOp op = new AffineTransformOp(tx,
                AffineTransformOp.TYPE_BICUBIC);
        image = op.filter(image, null);
        ImageIcon resultIcon = new ImageIcon(image);
        return resultIcon;
    }

    public InteractiveIcon mirrorHorizontal() {
        defaultIcon = mirrorHorizontal(defaultIcon);
        clearRolloverPressedIcons();
        return this;
    }

    public InteractiveIcon mirrorVertical() {
        defaultIcon = mirrorVertical(defaultIcon);
        clearRolloverPressedIcons();
        return this;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        defaultIcon.paintIcon(c, g, x, y);
    }

    @Override
    public int getIconWidth() {
        return defaultIcon.getIconWidth();
    }

    @Override
    public int getIconHeight() {
        return defaultIcon.getIconHeight();
    }

    private static BufferedImage convertImageToBufferedImage(ImageIcon icon) {
        BufferedImage newImage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics gr = newImage.getGraphics();
        gr.drawImage(icon.getImage(), 0, 0, null);
        gr.dispose();
        return newImage;
    }

    private static ImageIcon createRolloverIcon(ImageIcon icon) {
        BufferedImage image = convertImageToBufferedImage(icon);
        BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = (Graphics2D) result.getGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        int[] buf = ((DataBufferInt) result.getRaster().getDataBuffer()).getData();
        int w = result.getWidth();
        int h = result.getHeight();
        int pixelIndex = 0;
        int increase = 20;
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++, pixelIndex++) {
                int a = 0;
                int r = 0;
                int g = 0;
                int b = 0;
                int v = buf[pixelIndex];
                b = v & 0xFF;
                g = (v >> 8) & 0xFF;
                r = (v >> 16) & 0xFF;
                a = (v >> 24) & 0xFF;
                if (a != 0) {
                    r += increase;
                    g += increase;
                    b += increase;
                    if (r > 255) {
                        r = 255;
                    }
                    if (g > 255) {
                        g = 255;
                    }
                    if (b > 255) {
                        b = 255;
                    }
                    v = a;
                    v = v << 8;
                    v |= r;
                    v = v << 8;
                    v |= g;
                    v = v << 8;
                    v |= b;
                    buf[pixelIndex] = v;
                }
            }
        }

        ImageIcon resultIcon = new ImageIcon(result);
        return resultIcon;
    }

    private static ImageIcon createPressedIcon(ImageIcon icon) {
        BufferedImage image = convertImageToBufferedImage(icon);
        BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
        Graphics2D g2d = (Graphics2D) result.getGraphics();
        g2d.drawImage(image, 1, 1, image.getWidth() - 2, image.getHeight() - 2, null);
        g2d.dispose();
        return new ImageIcon(result);
    }
}


text:
// some helpers for testing various components that are hard to "mock"
// like databases and what not, here we have a docker compose "fire-upper"

package helper

import (
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestDockerUppers(t *testing.T) {

	Convey("Docker up and down", t, func() {

		ok := DockerUp("kafka")
		So(ok, ShouldEqual, true)

		ok = DockerWaitUntilReady("kafka")
		So(ok, ShouldEqual, true)

		ok = DockerDown("kafka")
		So(ok, ShouldEqual, true)
	})
}


text:
import { Directive } from '@angular/core';

@Directive({
  selector: 'mv-modal-body'
})
export class ModalBodyDirective {

  constructor() { }

}


text:
Roller coaster
=============


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/cxxtest/TestSuite.C $                                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

// Imported from FSP tree - /src/test/cxxtest/cxxtest/

#ifndef __cxxtest__TestSuite_cpp__
#define __cxxtest__TestSuite_cpp__

#include <limits.h>
#include <stdarg.h>
#include <arch/ppc.H>
#include <string.h>
#include <cxxtest/TestSuite.H>

trace_desc_t *g_trac_test = NULL;
TRAC_INIT(&g_trac_test, "UNIT_TEST", 4*KILOBYTE);

namespace CxxTest
{
/******************************************************************************/
// Globals/Constants
/******************************************************************************/
//This is a list of testcases that are expected to run in a serial manner
//   example: std::vector<const char *> CxxSerialTests{"libtestrtloader.so"};
//
//   libtesthwas, libtesteeprom, and libtestspiserial in serial bucket since
//   states may be altered which may adversely affect other tests
//
std::vector<const char *> CxxSerialTests{ "libtesthwas.so",
                                          "libtesteeprom.so",
                                          "libtestspiserial.so",
                                          "libtestfapi2serial.so",
                                          "libtestvpd.so",
                                          "libtestsbeio.so" };

//
// TestSuite members
//
TestSuite::~TestSuite() {}
void TestSuite::setUp() {}
void TestSuite::tearDown() {}

/**
 *
 *   @brief Implement trace action in unit tests
 *
 *   @return void
 *
 */
void doTrace( )
{

    __sync_add_and_fetch( &g_TraceCalls, 1 );

}

/**
 *
 *   @brief Implement warn action in unit tests
 *
 *   @param [in] pointer to filename  (not used right now )
 *   @param [in] line number
 *   @param [in] warning message
 *
 *   @return void
 *
 */
void doWarn( )
{

    __sync_add_and_fetch( &g_Warnings, 1 );

}

/**
 *   @brief Implement Fail action in unit tests
 *
 *   @return none
 */

void doFailTest( )
{

    TRACDCOMP( g_trac_test,
            "!!!       > Test Failed " );
    if(g_FailedTests < CXXTEST_FAIL_LIST_SIZE)
    {
        memcpy(g_FailedTestList[g_FailedTests].failTestFile,
               "---",
               3);
    }
    __sync_add_and_fetch( &g_FailedTests, 1 );

}

void sortTests(std::vector<const char *> & i_list,
               std::vector<const char *> & o_serial_list,
               std::vector<const char *> & o_parallel_list)
{
    o_serial_list.clear();
    o_serial_list.reserve(32);
    o_parallel_list.clear();
    o_parallel_list.reserve(32);

    //Loop through list of all tests
    for(std::vector<const char *>::const_iterator i = i_list.begin();
        i != i_list.end(); ++i)
    {
        bool is_serial = false;

        for(std::vector<const char *>::const_iterator j = CxxSerialTests.begin();
            j !=  CxxSerialTests.end(); ++j)
        {
            if (0 == strcmp(*i, *j))
            {
                is_serial = true;
            }
        }

        if (is_serial)
        {
            TRACFCOMP( g_trac_test, "%s is a serial test",*i);
            o_serial_list.push_back(*i);
        }
        else
        {
            TRACFCOMP( g_trac_test, "%s is a parallel test",*i);
            o_parallel_list.push_back(*i);
        }
    }
}

/**
 *   @brief Implement Fail action in unit tests
 *
 *   @param [in] pointer to filename  (not used right now )
 *   @param [in] line number
 *
 *   @return none
 */

void doFailTest( const char *filename, uint32_t linenum )
{
    TRACFCOMP( g_trac_test,
            "!!!       > Test %s Failed at line %d ",
            filename,
            linenum );

    if(g_FailedTests < CXXTEST_FAIL_LIST_SIZE)
    {
        memcpy(g_FailedTestList[g_FailedTests].failTestFile,
               filename,
               CXXTEST_FILENAME_SIZE);
        g_FailedTestList[g_FailedTests].failTestData = linenum;
    }
    __sync_add_and_fetch( &g_FailedTests, 1 );

}
/**
 *  @brief Report total number of unit tests in a test suite
 *
 *  A unit test suite will call this to report how many tests
 *  it has.  The call itself is autogenerated
 *
 *  @param [in] pointer to filename  (not used right now )
 *  @param [in] line number
 *  @param [in] trace message
 *
 *  @return void
 *
 *  @TODO do nothing with the suite name for now, later it may be useful
 *
 */
void reportTotalTests(  const char *suitename,
                        uint64_t numtests )
{

    __sync_add_and_fetch( &g_TotalTests, numtests );
    TRACDCOMP( g_trac_test,
            "Suite %s Completed ",
            suitename  );
    return;
}

};

#endif // __cxxtest__TestSuite_cpp__


text:
.. _contributing-chapter:

======================
Contributing to Waffle
======================

Waffle is pretty simple to hack, and has a decent test suite! Here's how to
hack Waffle, add tests, run them, and contribute changes.

Set Up
======

Setting up an environment is easy! You'll want ``virtualenv`` and ``pip``, then
just create a new virtual environment and install the requirements::

    $ mkvirtualenv waffle
    $ pip install -r requirements.txt

Done!

Running Things
==============

Waffle comes with a helper shell script to run tests and create schema
migrations: ``run.sh``. To run the tests, just::

    $ ./run.sh test

Run the script with no arguments to see all the options.

Writing Patches
===============

Patches should have tests. And follow PEP-8/existing styles. That's about it!
If you need help writing or running tests, let me know!

I will probably run your tests with and without the rest of the patch.

Submitting Patches
==================

Open a pull request on GitHub! If you want to make sure I'll merge the patch
upstream, open an issue first to discuss it.


text:
package org.ovirt.engine.ui.webadmin.section.main.view.popup.gluster;

import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeSnapshotConfig;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.idhandler.WithElementId;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel;
import org.ovirt.engine.ui.common.widget.editor.EntityModelCellTable;
import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor;
import org.ovirt.engine.ui.common.widget.renderer.NameRenderer;
import org.ovirt.engine.ui.common.widget.table.column.AbstractEntityModelTextColumn;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.gluster.GlusterClusterSnapshotConfigModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.gluster.GlusterClusterSnapshotConfigureOptionsPopupPresenterWidget;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextInputCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.NoSelectionModel;
import com.google.inject.Inject;

public class GlusterClusterSnapshotConfigureOptionsPopupView extends AbstractModelBoundPopupView<GlusterClusterSnapshotConfigModel> implements GlusterClusterSnapshotConfigureOptionsPopupPresenterWidget.ViewDef {
    interface Driver extends SimpleBeanEditorDriver<GlusterClusterSnapshotConfigModel, GlusterClusterSnapshotConfigureOptionsPopupView> {
    }

    interface ViewUiBinder extends UiBinder<SimpleDialogPanel, GlusterClusterSnapshotConfigureOptionsPopupView> {
        ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
    }

    interface ViewIdHandler extends ElementIdHandler<GlusterClusterSnapshotConfigureOptionsPopupView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @UiField
    @Ignore
    @WithElementId
    Label snapshotConfigHeader;

    @UiField(provided = true)
    @Path(value = "clusters.selectedItem")
    @WithElementId
    ListModelListBoxEditor<Cluster> clusterEditor;

    @UiField(provided = true)
    @Ignore
    @WithElementId
    EntityModelCellTable<ListModel<EntityModel<GlusterVolumeSnapshotConfig>>> configsTable;

    private static final ApplicationConstants constants = AssetProvider.getConstants();

    private final Driver driver = GWT.create(Driver.class);

    @Inject
    public GlusterClusterSnapshotConfigureOptionsPopupView(EventBus eventBus) {
        super(eventBus);
        initEditors();
        initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
        ViewIdHandler.idHandler.generateAndSetIds(this);
        localize();
        driver.initialize(this);
    }

    private void initEditors() {
        clusterEditor = new ListModelListBoxEditor<>(new NameRenderer<Cluster>());

        configsTable = new EntityModelCellTable<>(false, true);
        configsTable.setSelectionModel(new NoSelectionModel());

        configsTable.addColumn(new AbstractEntityModelTextColumn<GlusterVolumeSnapshotConfig>() {
            @Override
            public String getText(GlusterVolumeSnapshotConfig object) {
                return object.getParamName();
            }
        }, constants.volumeSnapshotConfigName(), "200px"); //$NON-NLS-1$

        Column<EntityModel<GlusterVolumeSnapshotConfig>, String> valueColumn = new Column<EntityModel<GlusterVolumeSnapshotConfig>, String>(new TextInputCell()) {
            @Override
            public String getValue(EntityModel<GlusterVolumeSnapshotConfig> object) {
                return object.getEntity().getParamValue();
            }
        };
        configsTable.addColumn(valueColumn, constants.volumeSnapshotConfigValue(), "100px"); //$NON-NLS-1$

        valueColumn.setFieldUpdater(new FieldUpdater<EntityModel<GlusterVolumeSnapshotConfig>, String>() {

            @Override
            public void update(int index, EntityModel<GlusterVolumeSnapshotConfig> object, String value) {
                object.getEntity().setParamValue(value);
            }
        });
    }

    private void localize() {
        clusterEditor.setLabel(constants.volumeClusterLabel());
        snapshotConfigHeader.setText(constants.snapshotConfigHeaderLabel());
    }

    @Override
    public void edit(final GlusterClusterSnapshotConfigModel object) {
        driver.edit(object);
        configsTable.asEditor().edit(object.getClusterConfigOptions());
    }

    @Override
    public GlusterClusterSnapshotConfigModel flush() {
        return driver.flush();
    }
}


text:
require 'twitter'

class Tweet < Naobot::Webhook::Base

  def initialize(*args)
    super
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
      config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
      config.access_token = ENV['TWITTER_ACCESS_TOKEN']
      config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
    end
  end

  def on_privmsg(message)
    if /^(twit\s|@)+([^\s]+)[\s]{0,}([\d]{0,})/ =~ message.body
      user = $2
      cnt = $3.to_i || 0

      twit = "#{user}: #{@client.user_timeline(user)[cnt].text.gsub(/\n/, ' ')}"
      notice(message.to, twit)
    end

  rescue => e
    notice(message.to, e.to_s)
  end
end


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

namespace SteamTrade.TradeOffer
{
    public class TradeOfferManager
    {
        private readonly HashSet<string> tradeOfferHistory = new HashSet<string>();
        private readonly OfferSession session;
        private readonly TradeOfferWebAPI webApi;

        public int LastTimeCheckedOffers { get; private set; }

        public TradeOfferManager(string apiKey, SteamWeb steamWeb)
        {
            if (apiKey == null)
                throw new ArgumentNullException("apiKey");

            webApi = new TradeOfferWebAPI(apiKey, steamWeb);
            session = new OfferSession(webApi, steamWeb);
        }

        public delegate void NewOfferHandler(TradeOffer offer);

        /// <summary>
        /// Occurs when a new trade offer has been made by the other user
        /// </summary>
        public event NewOfferHandler OnNewTradeOffer;

        /// <summary>
        /// Gets the currently active trade offers from the web api and processes them
        /// </summary>
        /// <returns></returns>
        public bool GetActiveTradeOffers()
        {
            var offers = webApi.GetActiveTradeOffers(false, true, false);
            if (offers != null && offers.TradeOffersReceived != null)
            {
                foreach (var offer in offers.TradeOffersReceived)
                {
                    if (offer.TradeOfferState == TradeOfferState.TradeOfferStateActive && !tradeOfferHistory.Contains(offer.TradeOfferId))
                    {
                        //make sure the api loaded correctly sometimes the items are missing
                        if (IsOfferValid(offer))
                        {
                            SendOfferToHandler(offer);
                        }
                        else
                        {
                            var resp = webApi.GetTradeOffer(offer.TradeOfferId);
                            if (IsOfferValid(resp.Offer))
                            {
                                SendOfferToHandler(resp.Offer);
                            }
                            else
                            {
                                //todo: log steam api is giving us invalid offers.
                                Debug.WriteLine("Offer returned from steam api is not valid : " + resp.Offer.TradeOfferId);
                            }
                        }
                    }
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Get any updated offers
        /// </summary>
        /// <param name="unixTimeStamp"></param>
        /// <returns></returns>
        public bool GetTradeOffersSince(int unixTimeStamp)
        {
            var offers = webApi.GetTradeOffers(false, true, false, true, false, unixTimeStamp.ToString());
            if (offers != null && offers.TradeOffersReceived != null)
            {
                foreach (var offer in offers.TradeOffersReceived)
                {
                    if (offer.TradeOfferState == TradeOfferState.TradeOfferStateActive && !tradeOfferHistory.Contains(offer.TradeOfferId))
                    {
                        //make sure the api loaded correctly sometimes the items are missing
                        if (IsOfferValid(offer))
                        {
                            SendOfferToHandler(offer);
                        }
                        else
                        {
                            var resp = webApi.GetTradeOffer(offer.TradeOfferId);
                            if (IsOfferValid(resp.Offer))
                            {
                                SendOfferToHandler(resp.Offer);
                            }
                            else
                            {
                                //todo: log steam api is giving us invalid offers.
                                Debug.WriteLine("Offer returned from steam api is not valid : " + resp.Offer.TradeOfferId);
                            }
                        }
                    }
                }
                return true;
            }
            return false;
        }

        public bool GetOffers()
        {
            if (LastTimeCheckedOffers != 0)
            {
                bool action = GetTradeOffersSince(LastTimeCheckedOffers);

                if (action)
                    LastTimeCheckedOffers = GetUnixTimeStamp();
                return action;
            }
            else
            {
                bool action = GetActiveTradeOffers();
                if (action)
                    LastTimeCheckedOffers = GetUnixTimeStamp();
                return action;
            }
        }

        private bool IsOfferValid(Offer offer)
        {
            if ((offer.ItemsToGive != null && offer.ItemsToGive.Count != 0)
                || (offer.ItemsToReceive != null && offer.ItemsToReceive.Count != 0))
            {
                return true;
            }
            return false;
        }

        private void SendOfferToHandler(Offer offer)
        {
            var tradeOffer = new TradeOffer(session, offer);
            tradeOfferHistory.Add(offer.TradeOfferId);
            OnNewTradeOffer(tradeOffer);
        }

        private int GetUnixTimeStamp()
        {
            return (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }

        public TradeOffer NewOffer(SteamID other)
        {
            var offer = new TradeOffer(session, other);
            return offer;
        }

        public bool GetOffer(string offerId, out TradeOffer tradeOffer)
        {
            tradeOffer = null;
            var resp = webApi.GetTradeOffer(offerId);
            if (resp != null)
            {
                if (IsOfferValid(resp.Offer))
                {
                    tradeOffer = new TradeOffer(session, resp.Offer);
                    return true;
                }
                else
                {
                    //todo: log steam api is giving us invalid offers.
                    Debug.WriteLine("Offer returned from steam api is not valid : " + resp.Offer.TradeOfferId);
                }
            }
            return false;
        }
    }
}


text:
Coin::Coin(const sf::Texture& texture) :
SwapEntity(texture)
{
    sprite.setSprite(5*16, 3*16, 0);

    hp = 1;
    maxHP = 1;
}

void Coin::updateCurrent(sf::Time dt, Context context)
{

}

void Coin::handleEventCurrent(const sf::Event& event, Context context)
{

}

void Coin::drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const
{

}


text:
package sandbox;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by Танечка on 15.03.2017.
 */
@Test
public class SquareTests {
    public void testArea(){
        Square s = new Square(5);
        Assert.assertEquals(s.area() ,25.0);

    }
}


text:
<?php
namespace MarkdownEditor\Event;

class OnRichTextEditorInit extends Event {

    public function process() {
        $this->modx->controller->addLexiconTopic('markdowneditor:default');

        $includeGFM = (int) $this->md->getOption('general.include_ghfmd_manager', null, 1);
        if ($includeGFM) {
            $this->modx->regClientCSS($this->md->getOption('cssUrl') . 'github-markdown.css');
        }

        $customCSS = $this->md->getOption('general.custom_css_manager', null, '');
        if (!empty($customCSS)) {
            $this->modx->regClientCSS($customCSS);
        }

        $oEmbedServices = $this->md->getEmbedServiceInstances();
        foreach ($oEmbedServices as $oEmbedService) {
            $oEmbedCSS = $oEmbedService->getCSS();

            foreach ($oEmbedCSS as $css) {
                $this->modx->regClientCSS($css);
            }
        }

        $this->modx->regClientCSS($this->md->getOption('cssUrl') . 'highlight.css');
        $this->modx->regClientCSS($this->md->getOption('cssUrl') . 'dependencies.css');
        $this->modx->regClientCSS($this->md->getOption('cssUrl') . 'app.css');

        $this->modx->regClientStartupScript($this->md->getOption('jsUrl') . 'mgr/dependencies.js');
        $this->modx->regClientStartupScript($this->md->getOption('jsUrl') . 'highlight.pack.js');
        $this->modx->regClientStartupScript($this->md->getOption('jsUrl') . 'mgr/acethemes.js');
        $this->modx->regClientStartupScript($this->md->getOption('jsUrl') . 'mgr/app.js');
    }
}


text:
from gcd import main
from pyannotate_runtime import collect_types

if __name__ == '__main__':
    collect_types.init_types_collection()
    with collect_types.collect():
        main()
    collect_types.dump_stats('type_info.json')


text:
require "formula"

class GoogleAppEngine < Formula
  homepage "https://developers.google.com/appengine/"
  url "https://storage.googleapis.com/appengine-sdks/featured/google_appengine_1.9.19.zip"
  sha256 "d1e17c90ce7ff0e1fcafedb59f74b4172db52709a07f9a4f2a2b46dc522ba94d"

  def install
    cd ".."
    share.install "google_appengine" => name
    %w[
      _python_runtime.py
      _php_runtime.py
      api_server.py
      appcfg.py
      bulkload_client.py
      bulkloader.py
      dev_appserver.py
      download_appstats.py
      endpointscfg.py
      gen_protorpc.py
      google_sql.py
      remote_api_shell.py
    ].each do |fn|
      bin.install_symlink share/name/fn
    end
  end
end


text:
NS_ASSUME_NONNULL_BEGIN

@interface SDLListFilesOperation ()

@property (weak, nonatomic) id<SDLConnectionManagerType> connectionManager;
@property (copy, nonatomic, nullable) SDLFileManagerListFilesCompletionHandler completionHandler;

@end

@implementation SDLListFilesOperation

- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager completionHandler:(nullable SDLFileManagerListFilesCompletionHandler)completionHandler {
    self = [super init];
    if (!self) {
        return nil;
    }

    _connectionManager = connectionManager;
    _completionHandler = completionHandler;

    return self;
}

- (void)start {
    [super start];

    [self sdl_listFiles];
}

- (void)sdl_listFiles {
    SDLListFiles *listFiles = [[SDLListFiles alloc] init];

    __weak typeof(self) weakSelf = self;
    [self.connectionManager sendManagerRequest:listFiles
                           withResponseHandler:^(__kindof SDLRPCRequest *request, __kindof SDLRPCResponse *response, NSError *error) {
                               SDLListFilesResponse *listFilesResponse = (SDLListFilesResponse *)response;
                               BOOL success = [listFilesResponse.success boolValue];
                               NSUInteger bytesAvailable = [listFilesResponse.spaceAvailable unsignedIntegerValue];
                               NSArray<NSString *> *fileNames = [NSArray arrayWithArray:listFilesResponse.filenames];

                               if (weakSelf.completionHandler != nil) {
                                   weakSelf.completionHandler(success, bytesAvailable, fileNames, error);
                               }

                               [weakSelf finishOperation];
                           }];
}

#pragma mark Property Overrides

- (nullable NSString *)name {
    return @"List Files";
}

- (NSOperationQueuePriority)queuePriority {
    return NSOperationQueuePriorityVeryHigh;
}

@end

NS_ASSUME_NONNULL_END


text:
package daemon

type Daemon struct {
	CIDR      string
	ExtraArgs string
}


text:
import { Component} from '@angular/core';
import { loginService } from '../../services/login.service' ;

@Component({
  selector:'logout',
  providers:[loginService],
  template: ''
})

export class LogoutComponent{

  constructor(private _loginService: loginService){}
  ngOnInit(){
      this._loginService.logout();
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>data storage in spark | Linda IT</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="article">
<meta property="og:title" content="data storage in spark">
<meta property="og:url" content="http://lindanxmu.github.io/2016/04/29/data-storage-in-spark/index.html">
<meta property="og:site_name" content="Linda IT">
<meta property="og:description">
<meta property="og:updated_time" content="2016-04-29T12:31:06.591Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="data storage in spark">
<meta name="twitter:description">

    <link rel="alternate" href="/atom.xml" title="Linda IT" type="application/atom+xml">

    <link rel="icon" href="/favicon.png">

    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="/css/style.css">

        Linda IT

          Home

          Archives

          Books

        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"></button><input type="hidden" name="sitesearch" value="http://lindanxmu.github.io"></form>

  <time datetime="2016-04-29T12:31:06.000Z" itemprop="datePublished">2016-04-29</time>

      data storage in spark

      Share

        Comments

      Newer

          CombineByKey action in spark

      Older

Linux Privilege Management Command

    Please enable JavaScript to view the comments powered by Disqus.

Tags

BigData

linux

spark

Tag Cloud

      BigData linux spark

Archives

May 2016

April 2016

Recent Posts

            CombineByKey action in spark

            data storage in spark

            Linux Privilege Management Command

      © 2016 DLin

      Powered by Hexo

    Home

    Archives

    Books

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">