text:
=begin
class CreditCard
  def initialize ( userNum )
    if userNum.to_s.size < 16
      raise ArgumentError.new( 'Card number not long enough!' )
    elsif userNum.to_s.size > 16
      raise ArgumentError.new( 'Card number too long!' )
    else
      remainder = userNum
      @cardNum = Array.new( 16 )
      @cardNum.each_index do |i|
        @cardNum[ i ] = remainder / ( 10 ** ( 15 - i ) )
        remainder = remainder % ( 10 ** ( 15 - i ) )
      end
    end
  end

  #DEFINE method#

#    ITERATE over every other element starting at first element
#      Multiple array element by two
#
#    Return array#
  def double_array
    return @cardNum.each_index.map do |i|
      if i % 2 == 0
        @cardNum[i] * 2
      else
        @cardNum[i]
      end
    end

  end

  def array_sum

    totalsum = double_array.inject(0) {
      |sum, x| sum += (x/10) + (x%10)
      }
  end

  def check_card
    array_sum % 10 == 0 ? true : false
  end

  def debug
    p @cardNum
    p double_array
    p array_sum
    p check_card
  end
end

=end
# Refactored Solution
class CreditCard
  def initialize ( userNum )
    if userNum.to_s.size < 16
      raise ArgumentError.new( 'Card number not long enough!' )
    elsif userNum.to_s.size > 16
      raise ArgumentError.new( 'Card number too long!' )
    else
      @cardNum = userNum.to_s.split('').map{|i| i.to_i}
    end
  end

  def double_array
     @cardNum.each_index.map { |i|
      i.even? ? @cardNum[i] * 2 : @cardNum[i]
      }
  end

  def array_sum
    totalsum = double_array.inject(0) {
      |sum, x| sum += (x/10) + (x%10)
      }
  end

  def check_card
    array_sum % 10 == 0 ? true : false
  end

  def debug
    p @cardNum
    p double_array
    p array_sum
    p check_card?
  end
end

# Reflection
#What was the most difficult part of this challenge for you and your pair?
# => We have very different work styles, and I think we clashed a bit during our pairing session. On my pair's end, I think he was stressed out with work and was focused on plowing through without realizing that he was cutting me out, and I think he had the impression that I wasn't very experienced, so didn't want to slow down for me although I was totally on top of what was going on.
# => We ended up taking much longer than necessary because we weren't in agreement on implementations, and I cancelled our second pairing session because I wasn't treated with respect for the first session and didn't want to be treated like that a second time. Fortunately, I sent him an email briefly explaining the situation and he came back with a very positive note, so we were able to clear the air quickly instead of railing on each other in our feedback and holding a grudge. This was a good learning experience for me, and validated what I assumed, that even though some people may underestimate my capabilities, possibly due to certain biases or stereotypes, they are not inherently bad people and often don't recognize their own assumptions. Starting a dialogue is more effective than getting mad and reciprocating the treatment.

#What new methods did you find to help you when you refactored?
# => Didn't implement any new methods but combined each_index and map together in a way that I hadn't used previously.
#What concepts or learnings were you able to solidify in this challenge?
#Whathile I have used the inject method before, I have usually used it to take a cumulative sum. In this method, I had to use inject(0) because my first sum couldn't simply equal the first element of the array, as there was some arithmetic manipulation that had to occur on the element first. Using the inject(0) method in this context finally clarified the purpose of inject(0), as I struggled a lot with this function when I was learning it on codeacademy.


text:
"use strict";

import prettyMs from 'pretty-ms';

import React from 'react';
import { Row } from 'react-bootstrap';
import { Col } from 'react-bootstrap';
import { ProgressBar } from 'react-bootstrap';

export default class TorrentTitleRow extends React.Component {
  render () {
    let torrent     = this.props.torrent;
    let timeRemaining = torrent.timeRemaining ?
      prettyMs(Math.round(torrent.timeRemaining), { compact: true }) :
      0
    let progress = torrent.progress ? Math.floor(torrent.progress * 100) : 0
    return (
      <Row>
        <Col md={3}>
          <ProgressBar
            striped
            bsStyle="success"
            now={progress}
            label="%(percent)s%"
          />
        </Col>
        <Col md={6}><strong>{torrent.name}</strong></Col>
        <Col md={3}>Time remaining: {timeRemaining}</Col>
      </Row>
    );
  }
};

TorrentTitleRow.propTypes = {
  torrent: React.PropTypes.object
};

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace htmlcxx;

class XmlParser
{
public:
	XmlParser(void);
	~XmlParser(void);

	static map<string, string> getLoginParams(const char* fileName);
	static string getLoginResult(const char* fileName);

	static void parseArticles(vector<Article>& items, const char* fileName);
	static void parseRecommends(map<string, string> bloggers, const char* fileName);
private:
	static tree<HTML::Node> createDom(const char* file);
	static void parseContents(vector<Article>& items,tree<HTML::Node>& dom);
};

#endif


text:
<!doctype html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>{% block title %}{% endblock %}</title>
  <meta name="description" content="">
  <meta name="author" content="">

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

  <link rel="shortcut icon" href="/static/favicon.ico">
  <link rel="apple-touch-icon" href="/static/apple-touch-icon.png">

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

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

    {% with messages = get_flashed_messages() %}
      {% if messages %}
        {% for message in messages %}

            ×
            {{ message }}

        {% endfor %}
      {% endif %}
    {% endwith %}

    {% include 'topnav.html' %}

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

            </button>
            Project name

Link

Link

Link

                Link

Login

Signup

Sidebar

Link

Link

Link

Link

Sidebar

Link

Link

Link

Link

Link

Link

Sidebar

Link

Link

Link

{% block header %}{% endblock %}

                    {% block main %}{% endblock %}

© Company 2014


text:
package com.intellij.codeInspection.htmlInspections;

import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.XmlSuppressableInspectionTool;
import com.intellij.codeInspection.XmlInspectionGroupNames;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.XmlElementVisitor;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlToken;
import com.intellij.psi.xml.XmlTokenType;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

/**
 * @author spleaner
 */
public abstract class HtmlLocalInspectionTool extends XmlSuppressableInspectionTool {

  @Override
  @Nls
  @NotNull
  public String getGroupDisplayName() {
    return XmlInspectionGroupNames.HTML_INSPECTIONS;
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  protected void checkTag(@NotNull final XmlTag tag, @NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    // should be overridden
  }

  protected void checkAttribute(@NotNull final XmlAttribute attribute, @NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    // should be overridden
  }

  @Override
  @NotNull
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    return new XmlElementVisitor() {
      @Override public void visitXmlToken(final XmlToken token) {
        if (token.getTokenType() == XmlTokenType.XML_NAME) {
          PsiElement element = token.getPrevSibling();
          while(element instanceof PsiWhiteSpace) element = element.getPrevSibling();

          if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_START_TAG_START) {
            PsiElement parent = element.getParent();

            if (parent instanceof XmlTag && !(token.getNextSibling() instanceof OuterLanguageElement)) {
              XmlTag tag = (XmlTag)parent;
              checkTag(tag, holder, isOnTheFly);
            }
          }
        }
      }

      @Override public void visitXmlAttribute(final XmlAttribute attribute) {
        checkAttribute(attribute, holder, isOnTheFly);
      }
    };
  }
}


text:
package io.bootique.meta.application;

import io.bootique.command.Command;
import io.bootique.meta.MetadataNode;
import io.bootique.names.ClassToName;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @since 0.20
 */
public class CommandMetadata implements MetadataNode {

    private String name;
    private String description;
    private String shortName;
    private boolean hidden;
    private Collection<OptionMetadata> options;

    public CommandMetadata() {
        this.options = new ArrayList<>();
    }

    public static Builder builder(Class<? extends Command> commandType) {
        return new Builder().commandType(commandType);
    }

    public static Builder builder(String commandName) {
        return new Builder().name(commandName);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescription() {
        return description;
    }

    /**
     * Returns an option representation of this command, that may be used in help generation or exposing the command
     * in a CLI parser.
     *
     * @return option representation of this command.
     * @since 0.21
     */
    public OptionMetadata asOption() {
        // TODO: cache the value?
        // using getters instead of vars ; some getters have logic
        return OptionMetadata.builder(getName()).shortName(getShortName()).description(getDescription()).build();
    }

    public Collection<OptionMetadata> getOptions() {
        return options;
    }

    /**
     * Returns the short name
     *
     * @return command short name.
     * @since 0.21
     */
    public String getShortName() {
        return (shortName != null) ? shortName : name.substring(0, 1);
    }

    /**
     * Returns whether the command should be hidden by default. Ultimately {@link io.bootique.command.CommandManager}
     * defines whether any given command is public or hidden. This property defines the default policy for the given
     * command.
     *
     * @return whether the command should be hidden by default.
     * @since 0.25
     */
    public boolean isHidden() {
        return hidden;
    }

    public static class Builder {

        private static ClassToName NAME_BUILDER = ClassToName
                .builder()
                .convertToLowerCase()
                .partsSeparator("-")
                .stripSuffix("Command")
                .build();

        private CommandMetadata command;

        private Builder() {
            this.command = new CommandMetadata();
        }

        public CommandMetadata build() {
            validateName(command.name);
            return command;
        }

        public Builder commandType(Class<? extends Command> commandType) {
            command.name = NAME_BUILDER.toName(commandType);
            return this;
        }

        public Builder name(String name) {
            command.name = validateName(name);
            return this;
        }

        public Builder shortName(char shortName) {
            command.shortName = String.valueOf(shortName);
            return this;
        }

        public Builder description(String description) {
            this.command.description = description;
            return this;
        }

        public Builder addOption(OptionMetadata option) {
            this.command.options.add(option);
            return this;
        }

        public Builder addOptions(Collection<OptionMetadata> options) {
            this.command.options.addAll(options);
            return this;
        }

        public Builder addOption(OptionMetadata.Builder optionBuilder) {
            return addOption(optionBuilder.build());
        }

        /**
         * @return this builder instance.
         * @since 0.25
         */
        public Builder hidden() {
            this.command.hidden = true;
            return this;
        }

        private String validateName(String name) {
            if (name == null) {
                throw new IllegalArgumentException("Null 'name'");
            }

            if (name.length() == 0) {
                throw new IllegalArgumentException("Empty 'name'");
            }

            return name;
        }
    }
}


text:
'use strict';

import { TPromise } from 'vs/base/common/winjs.base';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement';

export const ID = 'issueService';
export const IIssueService = createDecorator<IIssueService>(ID);

export enum IssueType {
	Bug,
	PerformanceIssue,
	FeatureRequest
}

export interface IssueReporterStyles {
	backgroundColor: string;
	color: string;
	textLinkColor: string;
	inputBackground: string;
	inputForeground: string;
	inputBorder: string;
	inputErrorBorder: string;
	inputActiveBorder: string;
	buttonBackground: string;
	buttonForeground: string;
	buttonHoverBackground: string;
	sliderBackgroundColor: string;
	sliderHoverColor: string;
	sliderActiveColor: string;
}

export interface IssueReporterData {
	styles: IssueReporterStyles;
	zoomLevel: number;
	enabledExtensions: ILocalExtension[];
	issueType?: IssueType;
}

export interface IIssueService {
	_serviceBrand: any;
	openReporter(data: IssueReporterData): TPromise<void>;
}


text:
var Utils = require('../src/utils')

describe('Utils', () => {
  describe('#isString', () => {
    it('correctly identifies a non-string as not a string', () => {
      var result = Utils.isString(1)
      expect(result).toBe(false)
    })

    it('correctly identifies a string as a string', () => {
      var result = Utils.isString('string')
      expect(result).toBe(true)
    })
  })

  describe('#isArray', () => {
    it('correctly identifies a non-array as not an array', () => {
      var result = Utils.isArray(1)
      expect(result).toBe(false)
    })

    it('correctly identifies an array literal as an array', () => {
      var result = Utils.isArray([])
      expect(result).toBe(true)
    })

    it('correctly identifies an array instance as an array', () => {
      var result = Utils.isArray([])
      expect(result).toBe(true)
    })

    describe('when isArray is not defined', function() {
      var originalIsArray

      beforeEach(() => {
        originalIsArray = Array.isArray
        Array.isArray = undefined
      })

      afterEach(() => {
        Array.isArray = originalIsArray
      })

      it('correctly identifies a non-array as not an array', () => {
        var result = Utils.isArray(1)
        expect(result).toBe(false)
      })

      it('correctly identifies an array literal as an array', () => {
        var result = Utils.isArray([])
        expect(result).toBe(true)
      })

      it('correctly identifies an array instance as an array', () => {
        var result = Utils.isArray([])
        expect(result).toBe(true)
      })
    })
  })

  describe('#isFunction', () => {
    it('correctly identifies a non-function as not a function', () => {
      var result = Utils.isFunction(1)
      expect(result).toBe(false)
    })

    it('correctly identifies a RegEx as not a function', () => {
      var result = Utils.isFunction(/something/)
      expect(result).toBe(false)
    })

    it('correctly identifies a function decleration as a function', () => {
      var result = Utils.isFunction(() => {})
      expect(result).toBe(true)
    })

    it('correctly identifies a function expression as a function', () => {
      var testCase = () => {}
      var result = Utils.isFunction(testCase)
      expect(result).toBe(true)
    })

    it('correctly identifies a method as a function', () => {
      var result = Utils.isFunction(Utils.isFunction)
      expect(result).toBe(true)
    })
  })

  describe('#isObject', () => {
    it('identifies an array as an Object type', () => {
      expect(Utils.isObject([])).toBe(true)
    })

    it('identifies an object literal as an Object type', () => {
      expect(Utils.isObject({})).toBe(true)
    })

    it('identifies the arguments object as an Object type', () => {
      expect(Utils.isObject(arguments)).toBe(true)
    })

    it('identifies a function as an Object type', () => {
      expect(Utils.isObject(() => {})).toBe(true)
    })

    it('identifies a regex as an Object type', () => {
      expect(Utils.isObject(/something/)).toBe(true)
    })

    it('identifies primitives and non-objects as not of type Object', () => {
      expect(Utils.isObject(1)).not.toBe(true)
      expect(Utils.isObject('something')).not.toBe(true)
      expect(Utils.isObject(false)).not.toBe(true)
      expect(Utils.isObject(undefined)).not.toBe(true)
      expect(Utils.isObject(null)).not.toBe(true)
    })

    it('identifies instances as Object types', () => {
      /* eslint-disable no-new-wrappers */
      expect(Utils.isObject(new Number(0))).toBe(true)
      expect(Utils.isObject(new String(''))).toBe(true)
      expect(Utils.isObject(new Boolean(''))).toBe(true)
      /* eslint-enable no-new-wrappers */
    })
  })

  describe('#extend', () => {
    it('extends an object with the attributes of another', () => {
      expect(Utils.extend({}, { a: 1 })).toEqual({ a: 1 })
    })

    it('overrides source properties with destination properties', () => {
      expect(Utils.extend({ a: 1 }, { a: 2 }).a).toBe(2)
    })

    it('maintains destination properties not in source', () => {
      expect(Utils.extend({ a: 1 }, { b: 2 }).a).toBeDefined()
    })

    it('can extend from multiple sources', () => {
      var result = Utils.extend({ a: 1 }, { b: 2 }, { c: 3})
      expect(result).toEqual({ a: 1, b: 2, c: 3})
    })

    it('sets property priority from right to left', () => {
      var result = Utils.extend({ a: 1 }, { a: 2, b: 2 }, { b: 3 })
      expect(result).toEqual({ a: 2, b: 3 })
    })

    it('skips over non-plain objects', () => {
      var result = Utils.extend({ a: 1 }, /something/, { b: 2 })
      expect(result).toEqual({ a: 1, b: 2 })
    })

    it('returns an empty object when arguments are not defined', () => {
      expect(Utils.extend()).toEqual({})
    })

    it('returns the original object when only one argument is passed', () => {
      var obj = {}
      expect(Utils.extend(obj)).toBe(obj)
    })

    it('copies all properties from source', () => {
      var obj = { a: 1 }
      obj.b = 2
      expect(Utils.extend({}, obj).a).toBe(1)
      expect(Utils.extend({}, obj).b).toBe(2)
    })

    it('does not extend inherited properties', () => {
      var F = function() {}
      F.prototype = { a: 1 }
      expect(Utils.extend({ a: 10 }, F).a).toEqual(10)
    })
  })

  describe('#clone', () => {
    it('clones a simple array', () => {
      var arr = [1, 2, 3]
      var result = Utils.clone(arr)
      expect(result).toEqual(arr)
    })

    it('clones object literals', () => {
      var obj = { a: 1, b: 2, c: 3 }
      var result = Utils.clone(obj)
      expect(result).toEqual(obj)
    })

    it('does not share shallow attributes between objects', () => {
      var obj = { a: 1 }
      var result = Utils.clone(obj)
      result.a = 10
      expect(obj.a === 1 && result.a === 10).toBe(true)
    })

    it('shares changes to deep attributes between objects', () => {
      var obj = { a: 1, b: 2, c: [1, 2, 3] }
      var result = Utils.clone(obj)
      result.c.push(4)
      expect(obj.c[obj.c.length - 1]).toBe(4)
    })

    it('does not clone non objects', () => {
      expect(Utils.clone(1)).toBe(1)
      expect(Utils.clone(undefined)).toBe(undefined)
      expect(Utils.clone('some string')).toBe('some string')
      expect(Utils.clone(null)).toBe(null)
      expect(Utils.clone(true)).toBe(true)
    })
  })

  describe('#each', () => {
    var once = ['once']

    describe('when iterating over an array', () => {
      var arr = [1, 2, 3]

      it('provides the value and iteration count to the iteratee', () => {
        var values = []
        var counts = []
        Utils.each(arr, (val, i) => {
          values.push(val)
          counts.push(++i)
        })
        expect(values).toEqual(arr)
        expect(counts).toEqual(arr)
      })

      it('accepts the context for the iteratee', () => {
        var obj = { add: 5 }
        var result = 0
        Utils.each(arr, function(val, i) {
          result += this.add
        }, obj)
        expect(result).toBe(15)
      })

      it('provides the collection to the iteratee', () => {
        Utils.each(once, (val, i, collection) => {
          expect(collection).toBe(once)
        })
      })

      it('iterates the length of the collection', () => {
        var spy = jasmine.createSpy('eachSpy')
        Utils.each(arr, (val, i) => spy())
        expect(spy.calls.count()).toBe(arr.length)
      })

      it('breaks out of iteration when `false` is returned', () => {
        var spy = jasmine.createSpy('eachSpy')

        Utils.each(arr, (val, i) => {
          spy(val)
          if (val === 2) {
            return false
          }
        })

        expect(spy.calls.count()).toBe(2)
        expect(spy).toHaveBeenCalledWith(1)
        expect(spy).toHaveBeenCalledWith(2)
        expect(spy).not.toHaveBeenCalledWith(3)
      })
    })

    describe('when iterating over an object', () => {
      var values = []
      var keys = []

      var ObjProto = {
        c: 3,
      }

      var obj = Object.create(ObjProto)
      obj.a = 1
      obj.b = 2

      Utils.each(obj, (v, k) => {
        values.push(v)
        keys.push(k)
      })

      it('provides the value and key to the iteratee', () => {
        expect(values).toEqual([1, 2])
        expect(keys).toEqual(['a', 'b'])
      })

      it('does not iterate over the inherited properites', () => {
        expect(values).not.toContain(3)
      })
    })

    it('is resiliant to collection property changes during iteration', () => {
      var changingObj = { 0: 0, 1: 1 }
      var count = 0
      Utils.each(changingObj, (v, k, collection) => {
        if (count < 10) {
          changingObj[++count] = v + 1
        }
      })
      expect(count).toBe(2)
      expect(changingObj).toEqual({ 0: 0, 1: 1, 2: 2 })
    })

    it('is resiliant to collection length changes during iteration', () => {
      var result = []
      var count = 0
      Utils.each(once, (v, i) => {
        if (count < 10) {
          result.push(++count)
        }
      })
      expect(count).toBe(1)
      expect(result).toEqual([1])
    })

    it('exits iteration when false is explicitly returned', () => {
      var result = 0
      Utils.each([1, 2], (v, i) => {
        if (i > 0) {
          return false
        }
        result += v
      })
      expect(result).toBe(1)
    })

    it('returns the collection', () => {
      expect(Utils.each(once, () => {})).toBe(once)
    })
  })

  describe('#partial', () => {
    it('partially applies function arguments', () => {
      var func = (greeting, name) => greeting + ' ' + name
      var result = Utils.partial(func, 'hello')
      expect(result('nuclear')).toBe('hello nuclear')
    })

    it('does not alter context', () => {
      var obj = { name: 'nuclear' }
      var func = function(greeting, mark) {
        return greeting + ' ' + this.name + mark
      }
      obj.greet = Utils.partial(func, 'hello')
      expect(obj.greet('!')).toBe('hello nuclear!')
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_rectangle_green_s" android:state_selected="true"></item>
    <item android:drawable="@drawable/bg_rectangle_green_s" android:state_pressed="true"></item>
    <item android:drawable="@drawable/bg_rectangle_green_s" android:state_focused="true"></item>
    <item android:drawable="@color/BIDDING_BG"></item>
</selector>


text:
package com.orientechnologies.orient.server.distributed;

import com.orientechnologies.orient.core.record.impl.ODocument;

import java.util.List;

/**
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 */
public interface ODistributedMessageService {
  public ODistributedRequest createRequest();

  long getLastMessageId();

  ODocument getQueueStats(String iQueueName);

  public ODistributedDatabase registerDatabase(String iDatabaseName);

  public ODistributedDatabase getDatabase(String iDatabaseName);

  public List<String> getManagedQueueNames();
}


text:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { DeploymentNewComponent } from './deployment-new.component';

describe('DeploymentNewComponent', () => {
  let component: DeploymentNewComponent;
  let fixture: ComponentFixture<DeploymentNewComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DeploymentNewComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DeploymentNewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
.PlaylistMeta {
  height: 54px;
  line-height: 54px;
  font-size: 14pt;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.PlaylistMeta-name {
  flex-grow: 1;
  padding-inline-start: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.PlaylistMeta-active {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-inline-end: 20px;
  height: 100%;
  cursor: pointer;

  &.is-active {
    cursor: default;
  }
}

/* Makes the element wrap tightly around its content, so we can put a <span /> around buttons that
 * may be `[disabled]`, and attach material-ui Tooltips to those spans instead. Without this, the
 * tooltip offsets would be calculated differently. */
.PlaylistMeta-possiblyDisabledButtonWrapper {
  display: flex;
}

.PlaylistMeta-iconButton {
  color: #555;

  &:hover {
    color: #fff;
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner;

import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.analyzer.Analysis;
import com.facebook.presto.sql.analyzer.FieldOrExpression;
import com.facebook.presto.sql.tree.Cast;
import com.facebook.presto.sql.tree.DereferenceExpression;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.ExpressionRewriter;
import com.facebook.presto.sql.tree.ExpressionTreeRewriter;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.QualifiedName;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.sql.QueryUtil.mangleFieldReference;
import static com.facebook.presto.type.TypeRegistry.isTypeOnlyCoercion;
import static com.google.common.base.Preconditions.checkState;

/**
 * Keeps track of fields and expressions and their mapping to symbols in the current plan
 */
class TranslationMap
{
    // all expressions are rewritten in terms of fields declared by this relation plan
    private final RelationPlan rewriteBase;
    private final Analysis analysis;

    // current mappings of underlying field -> symbol for translating direct field references
    private final Symbol[] fieldSymbols;

    // current mappings of sub-expressions -> symbol
    private final Map<Expression, Symbol> expressionMappings = new HashMap<>();

    public TranslationMap(RelationPlan rewriteBase, Analysis analysis)
    {
        this.rewriteBase = rewriteBase;
        this.analysis = analysis;

        fieldSymbols = new Symbol[rewriteBase.getOutputSymbols().size()];
    }

    public RelationPlan getRelationPlan()
    {
        return rewriteBase;
    }

    public void setFieldMappings(List<Symbol> symbols)
    {
        Preconditions.checkArgument(symbols.size() == fieldSymbols.length, "size of symbols list (%s) doesn't match number of expected fields (%s)", symbols.size(), fieldSymbols.length);

        for (int i = 0; i < symbols.size(); i++) {
            this.fieldSymbols[i] = symbols.get(i);
        }
    }

    public void copyMappingsFrom(TranslationMap other)
    {
        Preconditions.checkArgument(other.fieldSymbols.length == fieldSymbols.length,
                "number of fields in other (%s) doesn't match number of expected fields (%s)",
                other.fieldSymbols.length,
                fieldSymbols.length);

        expressionMappings.putAll(other.expressionMappings);
        System.arraycopy(other.fieldSymbols, 0, fieldSymbols, 0, other.fieldSymbols.length);
    }

    public Expression rewrite(Expression expression)
    {
        // first, translate names from sql-land references to plan symbols
        Expression mapped = translateNamesToSymbols(expression);

        // then rewrite subexpressions in terms of the current mappings
        return ExpressionTreeRewriter.rewriteWith(new ExpressionRewriter<Void>()
        {
            @Override
            public Expression rewriteExpression(Expression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
            {
                // convert expression to qualified name reference (containing a symbol) if rewrite registered
                Expression rewrittenExpression;
                Symbol symbol = expressionMappings.get(node);
                if (symbol != null) {
                    rewrittenExpression = new QualifiedNameReference(symbol.toQualifiedName());
                }
                else {
                    rewrittenExpression = treeRewriter.defaultRewrite(node, context);
                }

                return rewrittenExpression;
            }
        }, mapped);
    }

    public Expression rewrite(FieldOrExpression fieldOrExpression)
    {
        if (fieldOrExpression.isFieldReference()) {
            int fieldIndex = fieldOrExpression.getFieldIndex();
            Symbol symbol = fieldSymbols[fieldIndex];
            checkState(symbol != null, "No mapping for field '%s'", fieldIndex);

            return new QualifiedNameReference(symbol.toQualifiedName());
        }
        else {
            return rewrite(fieldOrExpression.getExpression());
        }
    }

    public void put(Expression expression, Symbol symbol)
    {
        Expression translated = translateNamesToSymbols(expression);
        expressionMappings.put(translated, symbol);

        // also update the field mappings if this expression is a field reference
        analysis.getFieldIndex(expression).ifPresent(index -> fieldSymbols[index] = symbol);
    }

    public void put(FieldOrExpression fieldOrExpression, Symbol symbol)
    {
        if (fieldOrExpression.isFieldReference()) {
            int fieldIndex = fieldOrExpression.getFieldIndex();
            fieldSymbols[fieldIndex] = symbol;
            expressionMappings.put(new QualifiedNameReference(rewriteBase.getSymbol(fieldIndex).toQualifiedName()), symbol);
        }
        else {
            put(fieldOrExpression.getExpression(), symbol);
        }
    }

    public Symbol get(Expression expression)
    {
        Expression translated = translateNamesToSymbols(expression);

        Preconditions.checkArgument(expressionMappings.containsKey(translated), "No mapping for expression: %s", expression);
        return expressionMappings.get(translated);
    }

    public Symbol get(FieldOrExpression fieldOrExpression)
    {
        if (fieldOrExpression.isFieldReference()) {
            int field = fieldOrExpression.getFieldIndex();
            Preconditions.checkArgument(fieldSymbols[field] != null, "No mapping for field: %s", field);
            return fieldSymbols[field];
        }
        else {
            return get(fieldOrExpression.getExpression());
        }
    }

    private Expression translateNamesToSymbols(Expression expression)
    {
        return ExpressionTreeRewriter.rewriteWith(new ExpressionRewriter<Void>()
        {
            @Override
            public Expression rewriteExpression(Expression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
            {
                Expression rewrittenExpression = treeRewriter.defaultRewrite(node, context);

                // cast expression if coercion is registered
                Type coercion = analysis.getCoercion(node);
                if (coercion != null) {
                    Type type = analysis.getType(node);
                    rewrittenExpression = new Cast(
                            rewrittenExpression,
                            coercion.getTypeSignature().toString(),
                            false,
                            isTypeOnlyCoercion(type.getTypeSignature(), coercion.getTypeSignature()));
                }

                return rewrittenExpression;
            }

            @Override
            public Expression rewriteQualifiedNameReference(QualifiedNameReference node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
            {
                return rewriteExpressionWithResolvedName(node);
            }

            private Expression rewriteExpressionWithResolvedName(Expression node)
            {
                Optional<Integer> fieldIndex = analysis.getFieldIndex(node);
                checkState(fieldIndex.isPresent(), "No field mapping for node '%s'", node);

                Symbol symbol = rewriteBase.getSymbol(fieldIndex.get());
                checkState(symbol != null, "No symbol mapping for node '%s' (%s)", node, fieldIndex.get());
                Expression rewrittenExpression = new QualifiedNameReference(symbol.toQualifiedName());

                // cast expression if coercion is registered
                Type coercion = analysis.getCoercion(node);
                if (coercion != null) {
                    rewrittenExpression = new Cast(rewrittenExpression, coercion.getTypeSignature().toString());
                }
                return rewrittenExpression;
            }

            @Override
            public Expression rewriteDereferenceExpression(DereferenceExpression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
            {
                if (analysis.getFieldIndex(node).isPresent()) {
                    return rewriteExpressionWithResolvedName(node);
                }

                // Rewrite all row field reference to function call.
                QualifiedName mangledName = QualifiedName.of(mangleFieldReference(node.getFieldName()));
                FunctionCall functionCall = new FunctionCall(mangledName, ImmutableList.of(node.getBase()));
                // hackish - add type for created node to analysis object so further rewriting does not fail
                IdentityHashMap<Expression, Type> functionType = new IdentityHashMap<>();
                functionType.put(functionCall, analysis.getType(node));
                analysis.addTypes(functionType);

                Expression rewrittenExpression = rewriteFunctionCall(functionCall, context, treeRewriter);

                // cast expression if coercion is registered
                Type type = analysis.getType(node);
                Type coercion = analysis.getCoercion(node);
                if (coercion != null) {
                    rewrittenExpression = new Cast(
                            rewrittenExpression,
                            coercion.getTypeSignature().toString(),
                            false,
                            isTypeOnlyCoercion(type.getTypeSignature(), coercion.getTypeSignature()));
                }
                return rewrittenExpression;
            }
        }, expression);
    }
}


text:
package org.infinispan.tx;

import org.infinispan.config.Configuration;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;

/**
 * @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
 * @since 5.1
 */
@Test (groups = "functional", testName = "tx.LockReleaseWithNoWriteTest")
public class LockReleaseWithNoWriteTest extends MultipleCacheManagersTest {

   @Override
   protected void createCacheManagers() throws Throwable {
      Configuration dcc = getDefaultClusteredConfig(Configuration.CacheMode.DIST_SYNC, true);
      dcc.fluent().transaction().lockingMode(LockingMode.PESSIMISTIC).syncCommitPhase(false);
      createCluster(dcc, 2);
      waitForClusterToForm();
   }

   public void testLocksReleased1() throws Exception {
      runtTest(1, 0);
   }
   public void testLocksReleased2() throws Exception {
      runtTest(1, 1);
   }
   public void testLocksReleased3() throws Exception {
      runtTest(0, 0);
   }
   public void testLocksReleased4() throws Exception {
      runtTest(0, 1);
   }

   private void runtTest(int lockOwner, int txOwner) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
      Object key = getKeyForCache(lockOwner);
      tm(txOwner).begin();
      advancedCache(txOwner).lock(key);
      tm(txOwner).commit();

      assertNotLocked(key);
   }
}


text:
/*	$NetBSD: getprotobyname_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $	*/

/*
 * Copyright (c) 1983, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)getprotoname.c	8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: getprotobyname_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $");
#endif
#endif /* LIBC_SCCS and not lint */

#include "namespace.h"

#include <assert.h>
#include <netdb.h>
#include <string.h>

#include "protoent.h"

#ifdef __weak_alias
__weak_alias(getprotobyname_r,_getprotobyname_r)
#endif

struct protoent *
getprotobyname_r(const char *name, struct protoent *pr,
    struct protoent_data *pd)
{
	struct protoent *p;
	char **cp;

	_DIAGASSERT(name != NULL);

	setprotoent_r(pd->stayopen, pd);
	while ((p = getprotoent_r(pr, pd)) != NULL) {
		if (strcmp(p->p_name, name) == 0)
			break;
		for (cp = p->p_aliases; *cp != NULL; cp++)
			if (strcmp(*cp, name) == 0)
				goto found;
	}
found:
	if (!pd->stayopen)
		if (pd->fp != NULL) {
			(void)fclose(pd->fp);
			pd->fp = NULL;
		}
	return p;
}


text:
/*
   colorPicker for script.aculo.us, version 1.0
   REQUIRES prototype.js, yahoo.color.js and script.aculo.us
   written by Matthias Platzer AT knallgrau.at
   for a detailled documentation go to http://www.knallgrau.at/code/colorpicker
 */

if(!Control) var Control = {};
Control.colorPickers = [];
Control.ColorPicker = Class.create();
Control.ColorPicker.activeColorPicker;
Control.ColorPicker.CONTROL;
/**
 * ColorPicker Control allows you to open a little inline popUp HSV color chooser.
 * This control is bound to an input field, that holds a hex value.
 */
Control.ColorPicker.prototype = {
  initialize : function(field, options) {
    var colorPicker = this;
    Control.colorPickers.push(colorPicker);
    this.field = field
    console.log(this.field)
    this.fieldName = this.field.name || this.field.id;
    this.options = Object.extend({
       IMAGE_BASE : "img/"
    }, options || {});
    this.swatch = $(this.options.swatch) || this.field;
    this.rgb = {};
    this.hsv = {};
    this.isOpen = false;
    // create control (popUp) if not already existing
    // all colorPickers on a page share the same control (popUp)
    if (!Control.ColorPicker.CONTROL) {
      Control.ColorPicker.CONTROL = {};
      if (!$("colorpicker")) {
        var control = Builder.node('div', {id: 'colorpicker'});
        control.innerHTML =
          '
' + (
            // apply png fix for ie 5.5 and 6.0
            (/MSIE ((6)|(5\.5))/gi.test(navigator.userAgent) && /windows/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) ?
              '' :
              ''
             ) +
          '

' +
          '

' +
          '

' +
          '
#<input type="text" onclick="this.select()" id="colorpicker-value-input" name="colorpicker-value" value=""></input><button id="colorpicker-okbutton">OK</button>
'
        document.body.appendChild(control);
      }
      Control.ColorPicker.CONTROL = {
        popUp : $("colorpicker"),
        pickerArea : $('colorpicker-div'),
        selector : $('colorpicker-selector'),
        okButton : $("colorpicker-okbutton"),
        value : $("colorpicker-value"),
        input : $("colorpicker-value-input"),
        picker : new Draggable($('colorpicker-selector'), {
          snap: function(x, y) {
            return [
              Math.min(Math.max(x, 0), Control.ColorPicker.activeColorPicker.control.pickerArea.offsetWidth),
              Math.min(Math.max(y, 0), Control.ColorPicker.activeColorPicker.control.pickerArea.offsetHeight)
            ];
          },
          zindex: 1009,
          change: function(draggable) {
            var pos = draggable.currentDelta();
            Control.ColorPicker.activeColorPicker.update(pos[0], pos[1]);
          }
        }),
        hueSlider: new Control.Slider('colorpicker-hue-thumb', 'colorpicker-hue-slider', {
          axis: 'vertical',
          onChange: function(v) {
            Control.ColorPicker.activeColorPicker.updateHue(v);
          }
        })
      };
      Element.hide($("colorpicker"));
    }
    this.control = Control.ColorPicker.CONTROL;

    // bind event listener to properties, so we can use them savely with Event[observe|stopObserving]
    this.toggleOnClickListener = this.toggle.bindAsEventListener(this);
    this.updateOnChangeListener = this.updateFromFieldValue.bindAsEventListener(this);
    this.closeOnClickOkListener = this.close.bindAsEventListener(this);
    this.updateOnClickPickerListener = this.updateSelector.bindAsEventListener(this);

    Event.observe(this.swatch, "click", this.toggleOnClickListener);
    Event.observe(this.field, "change", this.updateOnChangeListener);
    Event.observe(this.control.input, "change", this.updateOnChangeListener);

    this.updateSwatch();
  },
  toggle : function(event) {
    this[(this.isOpen) ? "close" : "open"](event);
    Event.stop(event);
  },
  open : function(event) {
    Control.colorPickers.each(function(colorPicker) {
      colorPicker.close();
    });
    Control.ColorPicker.activeColorPicker = this;
    this.isOpen = true;
    Element.show(this.control.popUp);
    if (this.options.getPopUpPosition) {
       var pos = this.options.getPopUpPosition.bind(this)(event);
    } else {
      var pos = Position.cumulativeOffset(this.swatch || this.field);
      pos[0] = (pos[0] + (this.swatch || this.field).offsetWidth + 10);
    }
    this.control.popUp.style.left = (pos[0]) + "px";
    this.control.popUp.style.top = (pos[1]) + "px";
    this.updateFromFieldValue();
    Event.observe(this.control.okButton, "click", this.closeOnClickOkListener);
    Event.observe(this.control.pickerArea, "mousedown", this.updateOnClickPickerListener);
    if (this.options.onOpen) this.options.onOpen.bind(this)(event);
  },
  close : function(event) {
    if (Control.ColorPicker.activeColorPicker == this) Control.ColorPicker.activeColorPicker = null;
    this.isOpen = false;
    Element.hide(this.control.popUp);
    Event.stopObserving(this.control.okButton, "click", this.closeOnClickOkListener);
    Event.stopObserving(this.control.pickerArea, "mousedown", this.updateOnClickPickerListener);
    if (this.options.onClose) this.options.onClose.bind(this)();
  },
  updateHue : function(v) {
    var h = (this.control.pickerArea.offsetHeight - v * 100) / this.control.pickerArea.offsetHeight;
    if (h == 1) h = 0;
    var rgb = YAHOO.util.Color.hsv2rgb( h, 1, 1 );
    if (!YAHOO.util.Color.isValidRGB(rgb)) return;
    this.control.pickerArea.style.backgroundColor = "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
    this.update();
  },
  updateFromFieldValue : function(event) {
    if (!this.isOpen) return;
    var field = (event && Event.findElement(event, "input")) || this.field;
    var rgb = YAHOO.util.Color.hex2rgb( field.value );
    if (!YAHOO.util.Color.isValidRGB(rgb)) return;
    var hsv = YAHOO.util.Color.rgb2hsv( rgb[0], rgb[1], rgb[2] );
    this.control.selector.style.left = Math.round(hsv[1] * this.control.pickerArea.offsetWidth) + "px";
    this.control.selector.style.top = Math.round((1 - hsv[2]) * this.control.pickerArea.offsetWidth) + "px";
    this.control.hueSlider.setValue((1 - hsv[0]));
  },
  updateSelector : function(event) {
    var xPos = Event.pointerX(event);
    var yPos = Event.pointerY(event);
    var pos = Position.cumulativeOffset($("colorpicker-bg"));
    this.control.selector.style.left = (xPos - pos[0] - 6) + "px";
    this.control.selector.style.top = (yPos - pos[1] - 6) + "px";
    this.update((xPos - pos[0]), (yPos - pos[1]));
    this.control.picker.initDrag(event);
  },
  updateSwatch : function() {
    var rgb = YAHOO.util.Color.hex2rgb( this.field.value );
    if (!YAHOO.util.Color.isValidRGB(rgb)) return;
    this.swatch.style.backgroundColor = "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
    var hsv = YAHOO.util.Color.rgb2hsv( rgb[0], rgb[1], rgb[2] );
    this.swatch.style.color = (hsv[2] > 0.65) ? "#000000" : "#FFFFFF";
  },
  update : function(x, y) {
    if (!x) x = this.control.picker.currentDelta()[0];
    if (!y) y = this.control.picker.currentDelta()[1];

    var h = (this.control.pickerArea.offsetHeight - this.control.hueSlider.value * 100) / this.control.pickerArea.offsetHeight;
    if (h == 1) { h = 0; };
    this.hsv = {
      hue: 1 - this.control.hueSlider.value,
      saturation: x / this.control.pickerArea.offsetWidth,
      brightness: (this.control.pickerArea.offsetHeight - y) / this.control.pickerArea.offsetHeight
    };
    var rgb = YAHOO.util.Color.hsv2rgb( this.hsv.hue, this.hsv.saturation, this.hsv.brightness );
    this.rgb = {
      red: rgb[0],
      green: rgb[1],
      blue: rgb[2]
    };
    this.field.value = YAHOO.util.Color.rgb2hex(rgb[0], rgb[1], rgb[2]);
    this.control.input.value = this.field.value;
    this.updateSwatch();
    if (this.options.onUpdate) this.options.onUpdate.bind(this)(this.field.value);
  }
}

$$('.color').each(function (el) {
  new Control.ColorPicker(el, {IMAGE_BASE: '/images/rails_admin/colorpicker/'});
});


text:
module ManageIQ::Providers::Lenovo
  class Inventory::Parser::ComponentParser::PhysicalChassis < Inventory::Parser::ComponentParser
    # Mapping between fields inside a [XClarity:PhysicalChassis] to a [Hash] with symbols of PhysicalChassis fields
    PHYSICAL_CHASSIS = {
      :name                         => 'name',
      :uid_ems                      => 'uuid',
      :ems_ref                      => 'uuid',
      :overall_health_state         => 'overallHealthState',
      :management_module_slot_count => 'mmSlots',
      :switch_slot_count            => 'switchSlots',
      :fan_slot_count               => 'fanSlots',
      :blade_slot_count             => 'bladeSlots',
      :powersupply_slot_count       => 'powerSupplySlots',
      :vendor                       => :vendor,
      # :type                         => :type,
      :health_state                 => :health_state,
      :computer_system              => {
        :hardware => {
          :guest_devices => nil, #:guest_devices
        }
      },
      :asset_detail                 => {
        :product_name     => 'productName',
        :manufacturer     => 'manufacturer',
        :machine_type     => 'machineType',
        :model            => 'model',
        :serial_number    => 'serialNumber',
        :contact          => 'contact',
        :description      => 'description',
        :location         => 'location.location',
        :room             => 'location.room',
        :rack_name        => 'location.rack',
        :lowest_rack_unit => 'location.lowestRackUnit'
      }
    }.freeze

    #
    # @param [Hash] chassis_hash - hash containing physical chassis raw data
    # @param [InventoryObject] rack - parsed physical rack data
    #
    def build(chassis_hash, rack)
      chassis_xclarity, properties = parse_physical_chassis(chassis_hash)

      add_parent(properties, :belongs_to => :physical_rack, :object => rack) if rack

      chassis = @persister.physical_chassis.build(properties)

      build_associations(chassis, chassis_xclarity)

      chassis
    end

    #
    # Parse a chassis hash to a hash with physical racks data
    #
    # @param [Hash] chassis_hash - hash containing physical chassis raw data
    #
    # @return [Hash] containing the physical server information
    #
    def parse_physical_chassis(chassis_hash)
      chassis = XClarityClient::Chassi.new(chassis_hash)
      result = parse(chassis, PHYSICAL_CHASSIS)

      [chassis, result]
    end

    private

    def build_associations(chassis, chassis_xclarity)
      comp_system = build_computer_system(chassis)
      build_hardware(comp_system, chassis_xclarity)
      build_asset_detail(chassis, chassis_xclarity)
    end

    def build_hardware(comp_system, chassis_xclarity)
      hw = @persister.physical_chassis_hardwares.build(
        :computer_system => comp_system
      )

      build_guest_devices(hw, chassis_xclarity)
    end

    def build_guest_devices(hardware, chassis_xclarity)
      components(:management_devices).build(chassis_xclarity,
                                            :physical_chassis_management_devices,
                                            :belongs_to => :hardware,
                                            :object     => hardware)
    end

    def build_asset_detail(hardware, chassis_xclarity)
      super(hardware, chassis_xclarity, PHYSICAL_CHASSIS[:asset_detail]) do |properties|
        properties.merge!(get_location_led_info(chassis_xclarity.leds) || {})
      end
    end

    def vendor(_chassis)
      'lenovo'
    end

    def type(_chassis)
      'ManageIQ::Providers::Lenovo::PhysicalInfraManager::PhysicalChassis'
    end

    def health_state(chassis)
      HEALTH_STATE_MAP[chassis.cmmHealthState.nil? ? chassis.cmmHealthState : chassis.cmmHealthState.downcase]
    end
  end
end


text:
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Zend_' => array($baseDir . '/libs'),
    'UnitTest' => array($vendorDir . '/mnapoli/phpdocreader/tests'),
    'Twig_' => array($vendorDir . '/twig/twig/lib'),
    'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
    'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
    'Symfony\\Bridge\\Monolog\\' => array($vendorDir . '/symfony/monolog-bridge'),
    'Psr\\Log\\' => array($vendorDir . '/psr/log'),
    'PhpDocReader' => array($vendorDir . '/mnapoli/phpdocreader/src'),
    'PEAR_' => array($baseDir . '/libs'),
    'PEAR' => array($vendorDir . '/pear/pear_exception'),
    'JShrink' => array($vendorDir . '/tedivm/jshrink/src'),
    'HTML_' => array($baseDir . '/libs'),
    'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib'),
    'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib'),
    'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib'),
    'Console' => array($vendorDir . '/pear/console_getopt'),
    'Archive_Tar' => array($vendorDir . '/pear/archive_tar'),
    'Archive_' => array($baseDir . '/libs'),
    '' => array($vendorDir . '/pear/pear-core-minimal/src'),
);


text:
using System;

namespace Ghul.Operations
{
	/// <summary>
	/// An operation that resets another when it has completed and thus will never complete.
	/// </summary>
	internal class LoopedOperation : Operation
	{
		/// <summary>
		/// The looped operation.
		/// </summary>
		private IOperation operation;

		/// <summary>
		/// Creates a new operation that resets another when it has completed.
		/// </summary>
		/// <param name="operation">The looped operation.</param>
		/// <exception cref="ArgumentNullException">If operation is null.</exception>
		public LoopedOperation(IOperation operation)
		{
			Ensure.IsNotNull(operation, nameof(operation));

			this.operation = operation;
		}

		/// <summary>
		/// Processes the operation based on the elapsed time.
		/// </summary>
		/// <param name="elapsedTime">The elapsed time.</param>
		/// <returns>The remaining time unused by the processing, must not be negative.</returns>
		/// <exception cref="ArgumentOutOfRangeException">If elapsedTime is negative.</exception>
		public override TimeSpan Process(TimeSpan elapsedTime)
		{
			Ensure.IsNotLessThan(elapsedTime, TimeSpan.Zero, nameof(elapsedTime));

			// Use up time until there is none left
			while(elapsedTime > TimeSpan.Zero)
			{
				elapsedTime = operation.Process(elapsedTime);

				// Reuse operation for next iteration by a simple reset
				if(operation.HasCompleted)
				{
					operation.Reset();
				}
			}

			return elapsedTime;
		}

		/// <summary>
		/// Resets the state.
		/// </summary>
		public override void Reset() => operation.Reset();
	}
}


text:
package com.todo.utils;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import cn.aigestudio.datepicker.bizs.calendars.DPCManager;
import cn.aigestudio.datepicker.bizs.decors.DPDecor;
import cn.aigestudio.datepicker.views.DatePicker;

/**
 * Created by tianyang on 2017/3/5.
 */
public class PickerUtil {

    //设置右上角圆点标志
    public static void setDPDecor(HashSet<DateTime> dateTimeList, DatePicker picker) {
        List<String> tmpTR = new ArrayList<>();
        for (DateTime dateTime : dateTimeList) {
            String year = dateTime.getYear() + "";
            String month = dateTime.getMonthOfYear() + "";
            String day = dateTime.getDayOfMonth() + "";
            tmpTR.add(year + "-" + month + "-" + day);
        }
        DPCManager.getInstance().setDecorTR(tmpTR);

        picker.setDPDecor(new DPDecor() {
            @Override
            public void drawDecorTL(Canvas canvas, Rect rect, Paint paint, String data) {
                super.drawDecorTL(canvas, rect, paint, data);
            }

            @Override
            public void drawDecorTR(Canvas canvas, Rect rect, Paint paint, String data) {
                super.drawDecorTR(canvas, rect, paint, data);
                paint.setColor(Color.parseColor("#45C01A"));
                canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 4, paint);
            }
        });

    }

}


text:
package ev3dev.actuators.lego.motors;

import ev3dev.hardware.EV3DevPlatforms;
import ev3dev.sensors.Battery;
import lejos.hardware.port.MotorPort;
import lejos.utility.Delay;

public class MultipleMotorsDemo extends EV3DevPlatforms {

    public static void main(String[] args) throws InterruptedException {

        MultipleMotorsDemo example = new MultipleMotorsDemo();

        System.out.println("Starting motor on A");
        final EV3LargeRegulatedMotor mA = new EV3LargeRegulatedMotor(MotorPort.A);
        System.out.println("Starting motor on B");
        final EV3LargeRegulatedMotor mB = new EV3LargeRegulatedMotor(MotorPort.B);

        //To Stop the motor in case of pkill java for example
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                mA.stop();
                mB.stop();
                System.out.println(Battery.getInstance().getVoltage());
            }
        }));

        mA.brake();
        mB.brake();

        mA.setSpeed(100);
        mB.setSpeed(100);
        mA.forward();
        mB.forward();

        Delay.msDelay(4000);
        mA.stop();
        mB.stop();
        System.out.println("Stopped motors");
    }

}


text:
package org.wso2.mb.integration.common.utils.ui.pages.configure;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.wso2.mb.integration.common.utils.ui.UIElementMapper;

public class AddRoleStep1Page {

    private static final Log log = LogFactory.getLog(AddRoleStep1Page.class);
    private WebDriver driver;

    public AddRoleStep1Page(WebDriver driver){
        this.driver = driver;
        if (!driver.findElement(By.xpath(UIElementMapper.getInstance().getElement("usr.mgt.add.role.step1.sub.header.xpath")))
                                                                            .getText().contains("Step 1 : Enter role details")) {
            throw new IllegalStateException("This is not the Add Role step1 page");
        }
    }

    public void setDetails(final String roleName) {
        driver.findElement(By.xpath(UIElementMapper.getInstance().getElement("usr.mgt.add.role.step1.name.field.xpath"))).sendKeys(roleName);
    }

    public AddRoleStep2Page next() {
        driver.findElement(By.xpath(UIElementMapper.getInstance().getElement("usr.mgt.add.role.step1.next.button.xpath"))).click();
        return new AddRoleStep2Page(driver);
    }
}


text:
package io.opensemantics.semiotics.model.assessment;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Sinks'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link io.opensemantics.semiotics.model.assessment.Sinks#getApplication Application}

 *
{@link io.opensemantics.semiotics.model.assessment.Sinks#getSinks Sinks}

 *

 *
 * @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getSinks()
 * @model
 * @generated
 */
public interface Sinks extends EObject {
	/**
   * Returns the value of the 'Application' reference.
   *
	 *

	 * If the meaning of the 'Application' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
   * @return the value of the 'Application' reference.
   * @see #setApplication(Application)
   * @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getSinks_Application()
   * @model
   * @generated
   */
	Application getApplication();

	/**
   * Sets the value of the '{@link io.opensemantics.semiotics.model.assessment.Sinks#getApplication Application}' reference.
   *
	 *
   * @param value the new value of the 'Application' reference.
   * @see #getApplication()
   * @generated
   */
	void setApplication(Application value);

	/**
   * Returns the value of the 'Sinks' containment reference list.
   * The list contents are of type {@link io.opensemantics.semiotics.model.assessment.Sink}.
   * It is bidirectional and its opposite is '{@link io.opensemantics.semiotics.model.assessment.Sink#getSinks Sinks}'.
   *
	 *

	 * If the meaning of the 'Sinks' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
   * @return the value of the 'Sinks' containment reference list.
   * @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getSinks_Sinks()
   * @see io.opensemantics.semiotics.model.assessment.Sink#getSinks
   * @model opposite="sinks" containment="true"
   * @generated
   */
	EList<Sink> getSinks();

} // Sinks


text:
import argparse
import sys

def get_options():
    parser = argparse.ArgumentParser(prog='smallest_largest_number.py',
                                     description=("Program to return" +
                                                  " the smallest and" +
                                                  " largest number from" +
                                                  " a list of numbers."))
    parser.add_argument('--built-in', action='store_true',
                        help=("Use built-in python sorted() or " +
                              "custom sort function; default " +
                              "behavior is custom sort function"))
    parser.add_argument('number', nargs='+',
                        type=float,
                        help="List of numbers")
    options = parser.parse_args()
    return options

def sort_em(list):
    """
    Function to find the smallest and largest values
    from an unsorted list of numbers.

    Function implements selection sort.  This sorting algorithm was chosen
    because of two factors:
    - storage efficiency
    - stable (i.e. any elements that are equal retain their initial relative
      ordering)
    """
    for position in range(len(list)-1, 0, -1):
        largest_seat = 0
        for seat in range(1, position+1):
            if list[seat] > list[largest_seat]:
                largest_seat = seat

        interim = list[position]
        list[position] = list[largest_seat]
        list[largest_seat] = interim

if __name__ == "__main__":
    options = get_options()
    if options.built_in:
        print "Smallest numeric value: " + str(sorted(options.number)[0])
        print "Largest numeric value: " + str(sorted(options.number)[-1])
    else:
        sort_em(options.number)
        print "Smallest numeric value: " + str(options.number[0])
        print "Largest numeric value: " + str(options.number[-1])
    sys.exit()


text:
module.exports = function (app, User, passportMiddleware) {
    return {
        getCurrent: [
            function (req, res, next) {
                if (!req.user) {
                    res.send(400);
                }
                else {
                    User.findOne({_id: req.user.id}, function (err, results) {
                        if (err) return next(err);
                        if (results) {
                            console.log({username: results.username});
                            res.send({username: results.username});
                        }
                        else {
                            res.send(400);
                        }
                    });
                }
            }],

        authenticate: [
            function (req, res, next) {
                passportMiddleware.authenticate('local', function (err, user, info) {
                    if (err) return next(err);
                    if (!user) {
                        return res.send('Invalid username or password.', 400);
                    }
                    req.logIn(user, function (err) {
                        if (err) return next(err);
                        return res.send('Ok', 200);
                    });
                })(req, res, next);
            }],

        create: [
            function (req, res, next) {
                var user = new User(req.body);
                User.findOne({username: user.username}, function (err, results) {
                    if (err) return next(err);
                    if (results) {
                        res.send('A user with this username already exists.', 400);
                    }
                    else {
                        user.save(function (err, results) {
                            if (err) return next(err);
                            req.logIn(user, function () {
                                res.send('ok', 200)
                            });
                        });
                    }
                })
            }],
        //logout/kill session
        kill: [
            function (req, res) {
                if (req.session) {
                    req.session.destroy(function () {
                        res.send('ok', 200)
                    });
                }
                else {
                    res.send('ok', 200)
                }
            }]
    };
};


text:
class Solution(object):
    def maxNumberOfApples(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        arr.sort()
        left = 5000
        count = 0

        for weight in arr:
            if left < weight:
                break
            left -= weight
            count += 1
        return count


text:
require 'ralyxa/response_entities/card'

RSpec.describe Ralyxa::ResponseEntities::Card do
  subject(:card) { described_class.as_hash }

  describe '.as_hash' do
    it 'generates a Simple card given only a title and body' do
      expected_result = {
        type: "Simple",
        title: "Hello Card",
        content: "Hello, string!"
      }

      simple_card = described_class.as_hash("Hello Card", "Hello, string!")
      expect(simple_card).to eq expected_result
    end

    it 'generates a Standard card given title, body, and an image hash' do
      expected_result = {
        type: "Standard",
        title: "Hello Card",
        text: "Hello, string!",
        image: {
          smallImageUrl: "https://image.url",
          largeImageUrl: "https://large.image.url"
        }
      }

      standard_card = described_class.as_hash("Hello Card", "Hello, string!", "https://image.url", "https://large.image.url")
      expect(standard_card).to eq expected_result
    end

    it 'raises an error if the card is given an image that does not start with https://' do
      Ralyxa.require_secure_urls = true

      expect { described_class.as_hash("Hello Card", "Hello, string!", "http://image.url", "http://large.image.url") }.to raise_error Ralyxa::UnsecureUrlError
    end

    context 'with an incomplete image hash' do
      it 'generates the expected standard card with a small and large image based on the small image' do
        expected_result = {
            type: "Standard",
            title: "Hello Card",
            text: "Hello, string!",
            image: {
                smallImageUrl: "https://image.url",
                largeImageUrl: "https://image.url"
            }
        }

        standard_card = described_class.as_hash("Hello Card", "Hello, string!", "https://image.url")
        expect(standard_card).to eq expected_result
      end

      it 'generates the expected standard card with a small and large image based on the large image' do
        expected_result = {
            type: "Standard",
            title: "Hello Card",
            text: "Hello, string!",
            image: {
                smallImageUrl: "https://large.image.url",
                largeImageUrl: "https://large.image.url"
            }
        }

        standard_card = described_class.as_hash("Hello Card", "Hello, string!", nil, "https://large.image.url")
        expect(standard_card).to eq expected_result
      end
    end
  end

  describe '.link_account' do
    it 'generates a LinkAccount card' do
      expected_result = {
        type: "LinkAccount"
      }

      link_account_card = described_class.link_account
      expect(link_account_card).to eq expected_result
    end
  end
end


text:
import six
from ...errors.httpconflictexception import HttpConflictException
import saklient

str = six.text_type
# module saklient.cloud.errors.deleteipv6netsfirstexception

class DeleteIpV6NetsFirstException(HttpConflictException):
    ## 要求された操作を行えません。ルータを削除する前に、IPv6ネットワークの割当を解除してください。

    ## @param {int} status
    # @param {str} code=None
    # @param {str} message=""
    def __init__(self, status, code=None, message=""):
        super(DeleteIpV6NetsFirstException, self).__init__(status, code, "要求された操作を行えません。ルータを削除する前に、IPv6ネットワークの割当を解除してください。" if message is None or message == "" else message)


text:
define(['exports', 'aurelia-dependency-injection', 'aurelia-templating', '../common/widget-base', '../common/decorators', '../common/constants', '../pdf/pdf'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _widgetBase, _decorators, _constants, _pdf) {
  'use strict';

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

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  var _dec, _dec2, _dec3, _class;

  var Scheduler = exports.Scheduler = (_dec = (0, _aureliaTemplating.customElement)(_constants.constants.elementPrefix + 'scheduler'), _dec2 = (0, _decorators.generateBindables)('kendoScheduler'), _dec3 = (0, _aureliaDependencyInjection.inject)(Element, _widgetBase.WidgetBase, _aureliaDependencyInjection.Container), _dec(_class = _dec2(_class = _dec3(_class = function () {
    function Scheduler(element, widgetBase, container) {
      _classCallCheck(this, Scheduler);

      this.element = element;
      this.widgetBase = widgetBase.control('kendoScheduler').useRootElement(this.element).linkViewModel(this).useContainer(container);
    }

    Scheduler.prototype.subscribe = function subscribe(event, callback) {
      return this.widgetBase.subscribe(event, callback);
    };

    Scheduler.prototype.bind = function bind(ctx, overrideCtx) {
      this.widgetBase.useParentCtx(overrideCtx);
    };

    Scheduler.prototype.attached = function attached() {
      var targets = this.element.querySelectorAll('div');
      if (targets.length > 0) {
        this.widgetBase.useElement(targets[0]);
      } else {
        var target = document.createElement('div');
        this.element.appendChild(target);
        this.widgetBase.useElement(target);
      }

      if (!this.kNoInit) {
        this.recreate();
      }
    };

    Scheduler.prototype.recreate = function recreate() {
      var templates = this.widgetBase.util.getChildrenVMs(this.element, _constants.constants.elementPrefix + 'template');
      this.widgetBase.useTemplates(this, 'kendoScheduler', templates);

      this.kWidget = this.widgetBase.recreate();
    };

    Scheduler.prototype.destroy = function destroy() {
      this.widgetBase.destroy(this.kWidget);
    };

    Scheduler.prototype.detached = function detached() {
      this.destroy();
    };

    return Scheduler;
  }()) || _class) || _class) || _class);
});


text:
import collections
import json

from anvil import shell as sh

class Helper(object):
    def __init__(self):
        self._executable = sh.which("explode_envra", ["tools/"])

    def explode(self, *filenames):
        if not filenames:
            return []
        cmdline = [self._executable]
        for filename in filenames:
            cmdline.append(sh.basename(filename))
        (stdout, _stderr) = sh.execute(cmdline)
        results = []
        missing = collections.deque(filenames)
        for line in stdout.splitlines():
            decoded = json.loads(line)
            decoded['origin'] = missing.popleft()
            results.append(decoded)
        if missing:
            raise AssertionError("%s filenames names were lost during"
                                 " exploding: %s" % (len(missing),
                                                     list(missing)))
        if len(results) > len(filenames):
            diff = len(results) - len(filenames)
            raise AssertionError("%s filenames appeared unexpectedly while"
                                 " exploding" % (diff))
        return results


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m131023_170033_initial extends Migration
{

    public function up()
    {
        $this->createTable('notification', array(
            'id' => 'pk',
            'class' => 'varchar(100) NOT NULL',
            'user_id' => 'int(11) NOT NULL',
            'seen' => 'tinyint(4) DEFAULT NULL',
            'source_object_model' => 'varchar(100) DEFAULT NULL',
            'source_object_id' => 'int(11) DEFAULT NULL',
            'target_object_model' => 'varchar(100) DEFAULT NULL',
            'target_object_id' => 'int(11) DEFAULT NULL',
            'space_id' => 'int(11) DEFAULT NULL',
            'emailed' => 'tinyint(4) NOT NULL',
            'created_at' => 'datetime NOT NULL',
            'created_by' => 'int(11) NOT NULL',
            'updated_at' => 'datetime NOT NULL',
            'updated_by' => 'int(11) NOT NULL',
                ), '');
    }

    public function down()
    {
        echo "m131023_170033_initial does not support migration down.\n";
        return false;
    }

    /*
      // Use safeUp/safeDown to do migration with transaction
      public function safeUp()
      {
      }

      public function safeDown()
      {
      }
     */
}


text:
<?php

declare(strict_types = 1);

namespace Reskume\FileBundle\Handler;

use Doctrine\ORM\EntityManager;
use Reskume\FileBundle\Entity\File;
use Reskume\FileBundle\Storage\FileStorageConfigurationInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class FileDownloadHandler
 *
 * Handles the download of files that are stored in the backend storage. Depending on the request
 * parameters, the handler will show the requested resource in the browser (default behavior). If requested,
 * the handler will trigger a file download.
 */
class FileDownloadHandler
{
    /**
     * @var FileStorageConfigurationInterface
     */
    private $configuration;
    /**
     * @var EntityManager
     */
    private $entityManager;
    /**
     * Indicates the HTML status code for the handled request.
     *
     * @var integer
     */
    private $responseCode = 200;
    /**
     * @var array
     */
    private $responseMessage = array();
    /**
     * Indicates current handler status.
     *
     * @var bool
     */
    private $error = false;
    /**
     * @var File
     */
    private $file;
    /**
     * @var string
     */
    private $filename;
    /**
     * @var mixed
     */
    private $fileContent;
    /**
     * @var bool
     */
    private $forceDownload;

    /**
     * @param FileStorageConfigurationInterface $configuration
     * @param EntityManager                     $entityManager
     */
    public function __construct(FileStorageConfigurationInterface $configuration, EntityManager $entityManager)
    {
        $this->configuration = $configuration;
        $this->entityManager = $entityManager;
    }

    /**
     * @param Request $request
     * @param string  $key file key
     *
     * @return $this
     */
    public function handle(Request $request, $key)
    {
        // get request param download if specified
        $forceDownload = $request->get('download');
        $this->forceDownload = ($forceDownload === 1 || $forceDownload === 'true') ?: false;

        // unless otherwise set, this handler will trigger a 404 file not found exception
        $this->setResponseCode(404);
        $this->responseMessage[] = sprintf(
            'The requested resource \'%s\' was not found on this server.',
            $this->filename
        );

        // try to find the requested File entity
        $this->file = $file = $this->entityManager
            ->getRepository('ReskumeFileBundle:File')
            ->findOneBy(array('key' => $key));

        if ($file instanceof File) {
            $fileStorage = $this->configuration->createFileStorage($this->entityManager);
            if ($this->fileContent = $fileStorage->getContent($file)) {
                $this->setResponseCode(200);
                $this->responseMessage = array();
            }
        }

        return $this;
    }

    /**
     * Convenient method to set status code. Additionally sets error property to true if status code is other than 200.
     *
     * @param int $code
     *
     * @return $this
     */
    private function setResponseCode(int $code)
    {
        $this->error = $code !== 200;
        $this->responseCode = $code;

        return $this;
    }

    /**
     * Get the Response object for the handled request.
     *
     * @return Response
     */
    public function getResponse(): Response
    {
        if ($this->error) {
            return new Response(implode(' ', $this->responseMessage), $this->responseCode);
        }

        $file = $this->file;

        // set headers
        $headers = ($this->forceDownload)
            ? array(
                'Content-Disposition' => 'Attachment;filename='.$file->getOrigFilename(),
                'Content-Type'        => $file->getMimeType(),
            )
            : array(
                'Content-Type' => $file->getMimeType()
            );

        return new Response(
            $this->fileContent,
            $this->responseCode,
            $headers
        );
    }
}


text:
package com.alow.dao.ofy;

import com.alow.dao.PessoaDao;
import com.alow.model.Pessoa;

public class PessoaOfyDao extends ObjectifyGenericDao<Pessoa,Long> implements PessoaDao{
	/*private EstadoDao estadoDao = DaoFactory.getEstadoDao();
	private CidadeDao cidadeDao = DaoFactory.getCidadeDao();*/

	public PessoaOfyDao(){
		super(Pessoa.class);
	}

	@Override
	public Pessoa getPessoaByGoogleUserId(String googleUserId) {
		return getByProperty("googleUserId", googleUserId);
	}

}