text:
package ee.ioc.phon.android.speak;

import java.net.MalformedURLException;
import java.net.URL;

import ee.ioc.phon.android.speak.provider.Grammar;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 *
This activity lists all the grammar URLs and allows the
 * user to add more. The list data comes from the Grammar-table
 * via the standard SimpleCursorAdapter. Long-tapping on a
 * list item allows the user to:

 *
 *

 *
view the content of the grammar (in a browser)

 *
edit the entry, i.e. the name, URL, etc.

 *
delete the entry

 *

 *
 * @author Kaarel Kaljurand
 */
public class GrammarListActivity extends RecognizerIntentListActivity {

	private static final Uri CONTENT_URI = Grammar.Columns.CONTENT_URI;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String[] columns = new String[] {
				Grammar.Columns._ID,
				Grammar.Columns.NAME,
				Grammar.Columns.LANG,
				Grammar.Columns.DESC,
				Grammar.Columns.URL
		};

		int[] to = new int[] {
				R.id.itemGrammarId,
				R.id.itemGrammarName,
				R.id.itemGrammarLang,
				R.id.itemGrammarDesc,
				R.id.itemGrammarUrl
		};

		Cursor managedCursor = managedQuery(
				CONTENT_URI,
				columns,
				null,
				null,
				Grammar.Columns.NAME + " ASC"
		);

		SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(
				this,
				R.layout.list_item_grammar,
				managedCursor,
				columns,
				to
		);

		ListView lv = getListView();
		setEmptyView(getString(R.string.emptylistGrammars));
		lv.setAdapter(mAdapter);

		registerForContextMenu(lv);
		setClickToFinish(CONTENT_URI, Grammar.Columns._ID);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.grammars, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuGrammarsAdd:
			Utils.getTextEntryDialog(
					this,
					getString(R.string.dialogTitleNewGrammar),
					"",
					new ExecutableString() {
						public void execute(String url) {
							if (url.length() > 0) {
								try {
									new URL(url);
									String name = url.replaceFirst(".*\\/", "").replaceFirst("\\.[^.]*$", "");
									ContentValues values = new ContentValues();
									values.put(Grammar.Columns.NAME, name);
									values.put(Grammar.Columns.URL, url);
									insert(CONTENT_URI, values);
								} catch (MalformedURLException e) {
									toast(getString(R.string.exceptionMalformedUrl));
								}
							}
						}
					}
			).show();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.cm_grammar, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		Cursor cursor = (Cursor) getListView().getItemAtPosition(info.position);
		final long key = cursor.getLong(cursor.getColumnIndex(Grammar.Columns._ID));
		String name = cursor.getString(cursor.getColumnIndex(Grammar.Columns.NAME));
		String grammarName = cursor.getString(cursor.getColumnIndex(Grammar.Columns.NAME));
		String grammarLang = cursor.getString(cursor.getColumnIndex(Grammar.Columns.LANG));
		String grammarUrl = cursor.getString(cursor.getColumnIndex(Grammar.Columns.URL));

		switch (item.getItemId()) {
		case R.id.cmGrammarView:
			Intent intentView = new Intent();
			intentView.setAction(android.content.Intent.ACTION_VIEW);
			intentView.setDataAndType(Uri.parse(grammarUrl), "text/plain");
			startActivity(intentView);
			return true;
		case R.id.cmGrammarEditName:
			Utils.getTextEntryDialog(
					this,
					getString(R.string.dialogTitleChangeGrammarName),
					grammarName,
					new ExecutableString() {
						public void execute(String name) {
							if (name != null && name.length() == 0) {
								name = null;
							}
							update(CONTENT_URI, key, Grammar.Columns.NAME, name);
						}
					}
			).show();
			return true;
		case R.id.cmGrammarEditLang:
			Utils.getTextEntryDialog(
					this,
					getString(R.string.dialogTitleChangeGrammarLang),
					grammarLang,
					new ExecutableString() {
						public void execute(String lang) {
							if (lang != null && lang.length() == 0) {
								lang = null;
							}
							update(CONTENT_URI, key, Grammar.Columns.LANG, lang);
						}
					}
			).show();
			return true;
		case R.id.cmGrammarEditUrl:
			Utils.getTextEntryDialog(
					this,
					getString(R.string.dialogTitleChangeGrammarUrl),
					grammarUrl,
					new ExecutableString() {
						public void execute(String newUrl) {
							try {
								updateUrl(CONTENT_URI, key, Grammar.Columns.URL, newUrl);
							} catch (MalformedURLException e) {
								toast(getString(R.string.exceptionMalformedUrl));
							}
						}
					}
			).show();
			return true;
		case R.id.cmGrammarDelete:
			Utils.getYesNoDialog(
					this,
					String.format(getString(R.string.confirmDeleteEntry), name),
					new Executable() {
						public void execute() {
							delete(CONTENT_URI, key);
						}
					}
			).show();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
var sequelize = require('../database');
var Sequelize = require('sequelize');
var User = require('./user');

var Like = sequelize.define('likes', {
  id: {
    type: Sequelize.INTEGER,
    field: 'id',
    primaryKey: true,
    autoIncrement: true
  },
  value: {
    type: Sequelize.INTEGER,
    field: 'value'
  },
}, {
  tableName: 'likes'
});

Like.belongsTo(User);

Like.getLikeWithUser = function(id) {
  return Like.findOne({ where: {id: id}, include: [{model: User, attributes: ['username']}]})
}

module.exports = Like;


text:
<?php

/**
 * The "jobs" collection of methods.
 * Typical usage is:
 *  <code>
 *   $mlService = new Google_Service_CloudMachineLearning(...);
 *   $jobs = $mlService->jobs;
 *  </code>
 */
class Google_Service_CloudMachineLearning_Resource_ProjectsJobs extends Google_Service_Resource
{
  /**
   * Cancels a running job. (jobs.cancel)
   *
   * @param string $name Required. The name of the job to cancel.
   *
   * Authorization: requires `Editor` role on the parent project.
   * @param Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1CancelJobRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudMachineLearning_GoogleProtobufEmpty
   */
  public function cancel($name, Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1CancelJobRequest $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('cancel', array($params), "Google_Service_CloudMachineLearning_GoogleProtobufEmpty");
  }
  /**
   * Creates a training or a batch prediction job. (jobs.create)
   *
   * @param string $parent Required. The project name.
   *
   * Authorization: requires `Editor` role on the specified project.
   * @param Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job
   */
  public function create($parent, Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job $postBody, $optParams = array())
  {
    $params = array('parent' => $parent, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job");
  }
  /**
   * Describes a job. (jobs.get)
   *
   * @param string $name Required. The name of the job to get the description of.
   *
   * Authorization: requires `Viewer` role on the parent project.
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1Job");
  }
  /**
   * Lists the jobs in the project. (jobs.listProjectsJobs)
   *
   * @param string $parent Required. The name of the project for which to list
   * jobs.
   *
   * Authorization: requires `Viewer` role on the specified project.
   * @param array $optParams Optional parameters.
   *
   * @opt_param int pageSize Optional. The number of jobs to retrieve per "page"
   * of results. If there are more remaining results than this number, the
   * response message will contain a valid value in the `next_page_token` field.
   *
   * The default value is 20, and the maximum page size is 100.
   * @opt_param string filter Optional. Specifies the subset of jobs to retrieve.
   * @opt_param string pageToken Optional. A page token to request the next page
   * of results.
   *
   * You get the token from the `next_page_token` field of the response from the
   * previous call.
   * @return Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1ListJobsResponse
   */
  public function listProjectsJobs($parent, $optParams = array())
  {
    $params = array('parent' => $parent);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_CloudMachineLearning_GoogleCloudMlV1beta1ListJobsResponse");
  }
}


text:
"""Convenience namespace module for importing Python class implementations"""

__all__ = ('Vec2', 'Point', 'Vec2Array', 'Seq2',
	'Affine', 'Line', 'Ray', 'LineSegment', 'BoundingBox', 'Polygon')

from planar.vector import Vec2, Vec2Array, Seq2
from planar.vector import Vec2 as Point
from planar.transform import Affine
from planar.line import Line, Ray, LineSegment
from planar.box import BoundingBox
from planar.polygon import Polygon


text:
from django import forms
from django import http
from django.core import urlresolvers
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from satchmo_store.mail import send_store_mail
from satchmo_store.shop.signals import contact_sender
import logging

log = logging.getLogger('satchmo_store.shop.views')

# Choices displayed to the user to categorize the type of contact request.
email_choices = (
    ("General Question", _("General question")),
    ("Order Problem", _("Order problem")),
)

class ContactForm(forms.Form):
    name = forms.CharField(label=_("Name"), max_length=100)
    sender = forms.EmailField(label=_("Email address"), max_length=75)
    subject = forms.CharField(label=_("Subject"))
    inquiry = forms.ChoiceField(label=_("Inquiry"), choices=email_choices)
    contents = forms.CharField(label=_("Contents"), widget=
        forms.widgets.Textarea(attrs={'cols': 40, 'rows': 5}))

def form(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            new_data = form.cleaned_data
            c = {
                'request_type': new_data['inquiry'],
                'name': new_data['name'],
                'email': new_data['sender'],
                'request_text': new_data['contents'] }
            subject = new_data['subject']
            send_store_mail(subject, c, 'shop/email/contact_us.txt',
                            send_to_store=True, sender=contact_sender)
            url = urlresolvers.reverse('satchmo_contact_thanks')
            return http.HttpResponseRedirect(url)
    else: #Not a post so create an empty form
        initialData = {}
        if request.user.is_authenticated():
            initialData['sender'] = request.user.email
            initialData['name'] = request.user.first_name + " " + request.user.last_name
        form = ContactForm(initial=initialData)

    return render_to_response('shop/contact_form.html', {'form': form},
                              context_instance=RequestContext(request))


text:
'use strict';

const path = require('path');
const ensurePosixPath = require('ensure-posix-path');

module.exports = function resolvePath(importPath, fromFile, options) {
  let pathWithExtension = path.extname(importPath)
    ? importPath
    : importPath + '.' + options.defaultExtension;

  if (isRelativePath(pathWithExtension)) {
    return resolveRelativePath(pathWithExtension, fromFile, options);
  } else if (isLocalPath(pathWithExtension, options)) {
    return resolveLocalPath(pathWithExtension, fromFile, options);
  } else if (isLocalPathWithOldPackageNameRef(pathWithExtension, options)) {
    const amendedPathWithExtension = pathWithExtension.replace(
      options.parentName,
      options.ownerName
    );
    options.ui.writeWarnLine(
      'For addons that define a moduleName, you should reference any CSS Modules provided by that addon ' +
        'using its moduleName instead of the package name.\n' +
        'Current path: ' +
        importPath +
        '\n' +
        'Replace with: ' +
        importPath.replace(options.parentName, options.ownerName) +
        '\n' +
        'File: ' +
        fromFile
    );
    return resolveLocalPath(amendedPathWithExtension, fromFile, options);
  } else {
    return resolveExternalPath(
      pathWithExtension,
      importPath,
      fromFile,
      options
    );
  }
};

function isRelativePath(importPath) {
  return /^\.\.?\//.test(importPath);
}

function isLocalPath(importPath, options) {
  return importPath.indexOf(options.ownerName + '/') === 0;
}

function isLocalPathWithOldPackageNameRef(importPath, options) {
  return (
    options.ownerName !== options.parentName &&
    importPath.indexOf(options.parentName + '/') === 0
  );
}

function resolveRelativePath(importPath, fromFile, options) {
  let absolutePath = ensurePosixPath(
    path.resolve(path.dirname(fromFile), importPath)
  );
  return internalDep(absolutePath, options);
}

// Resolve absolute paths pointing to the same app/addon as the importer
function resolveLocalPath(importPath, fromFile, options) {
  const fromFileStartsWithOwnerName = fromFile
    .substring(options.root.length + 1)
    .startsWith(options.ownerName);

  // Depending on the exact version of Ember CLI and/or Embroider in play, the
  // app/addon name may or may not be included in `fromFile`'s path. If not, we
  // need to strip that prefix from the import path.
  if (!fromFileStartsWithOwnerName) {
    importPath = importPath.substring(options.ownerName.length + 1);
  }

  let absolutePath = ensurePosixPath(path.resolve(options.root, importPath));
  return internalDep(absolutePath, options);
}

// Resolve absolute paths pointing to external addons
function resolveExternalPath(importPath, originalPath, fromFile, options) {
  let baseIndex = importPath[0] === '@' ? importPath.indexOf('/') + 1 : 0;
  let addonName = importPath.substring(0, importPath.indexOf('/', baseIndex));
  let addon = options.parent.addons.find((addon) => {
    if (addon.moduleName) {
      return addon.moduleName() === addonName;
    }
    return addon.name === addonName;
  });

  if (!addon) {
    throw new Error(
      `Unable to resolve styles module '${originalPath}' imported from '${fromFile}'. ` +
        `No virtual module with that name was defined and no corresponding addon was found.`
    );
  }

  let pathWithinAddon = importPath.substring(addonName.length + 1);
  let addonTreePath = path.join(addon.root, addon.treePaths.addon);

  let absolutePath = ensurePosixPath(
    path.resolve(addonTreePath, pathWithinAddon)
  );
  let keyPath = addonName + '/' + pathWithinAddon;
  return new DependencyPath('external', absolutePath, keyPath);
}

function internalDep(absolutePath, options) {
  let keyPath = absolutePath.substring(options.root.length + 1);
  return new DependencyPath('internal', absolutePath, keyPath);
}

class DependencyPath {
  constructor(type, absolutePath, keyPath) {
    this.type = type;
    this.absolutePath = absolutePath;
    this.keyPath = keyPath;
  }

  toString() {
    return this.absolutePath;
  }
}


text:
NSString * FASettingsPluginEnabledDidChangeNotification = @"io.github.FuzzyAutocomplete.PluginEnabledDidChange";

// increment to show settings screen to the user
static const NSUInteger kSettingsVersion = 4;

@interface FASettings () <NSWindowDelegate>

@end

@implementation FASettings

+ (instancetype) currentSettings {
    static FASettings * settings;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        settings = [FASettings new];
    });
    return settings;
}

#pragma mark - settings window

- (void) showSettingsWindow {
    [[NSUserDefaults standardUserDefaults] setObject: @(kSettingsVersion) forKey: kSettingsVersionKey];
    [self loadFromDefaults];
    NSBundle * bundle = [NSBundle bundleForClass: [self class]];
    NSArray * objects;
    NSWindow * window = nil;
    @try {
        [bundle loadNibNamed: @"FASettingsWindow" owner: self topLevelObjects: &objects];
        for (id object in objects) {
            if ([object isKindOfClass: [NSWindow class]]) {
                window = object;
                break;
            }
        }
    }
    @catch (NSException *exception) {
        RLog(@"Exception while opening Settings Window: %@", exception);
    }

    if (window) {
        window.minSize = window.frame.size;
        window.maxSize = window.frame.size;
        NSString * title = bundle.lsl_bundleNameWithVersion;
        NSTextField * label = (NSTextField *) [window.contentView viewWithTag: 42];
        NSMutableAttributedString * attributed = [[NSMutableAttributedString alloc] initWithString: title];
        FATheme * theme = [FATheme cuurrentTheme];
        [attributed addAttributes: theme.listTextAttributesForMatchedRanges range: NSMakeRange(0, 1)];
        [attributed addAttributes: theme.listTextAttributesForMatchedRanges range: NSMakeRange(5, 1)];
        [attributed addAttributes: theme.previewTextAttributesForNotMatchedRanges range: NSMakeRange(18, title.length-18)];
        NSMutableParagraphStyle * style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        style.alignment = NSCenterTextAlignment;
        [attributed addAttribute: NSParagraphStyleAttributeName value: style range: NSMakeRange(0, attributed.length)];
        label.attributedStringValue = attributed;

        BOOL enabled = self.pluginEnabled;

        [NSApp runModalForWindow: window];

        if (self.pluginEnabled != enabled) {
            [[NSNotificationCenter defaultCenter] postNotificationName: FASettingsPluginEnabledDidChangeNotification object: self];
        }

        [[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        NSString * reportIssueURL = [bundle objectForInfoDictionaryKey: @"FAReportIssueURL"];
        if (reportIssueURL) {
            NSAlert * alert = [NSAlert alertWithMessageText: [NSString stringWithFormat: @"Failed to open %@ settings.", bundle.lsl_bundleName]
                                              defaultButton: @"OK"
                                            alternateButton: @"Report an Issue"
                                                otherButton: nil
                                  informativeTextWithFormat: @"This might happen when updating the plugin to a newer version. To completely load the new plugin Xcode restart is required.\n\nIf the issue persists after a restart please report an issue."];
            if ([alert runModal] == NSAlertAlternateReturn) {
                [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: reportIssueURL]];
            }
        }
    }
}

- (void) windowWillClose: (NSNotification *) notification {
    NSWindow * window = notification.object;
    [window makeFirstResponder: window.contentView];
    [NSApp stopModal];
}

#pragma mark - defaults

static const BOOL kDefaultPluginEnabled = YES;

static const double kDefaultMinimumScoreThreshold = 0.01;
static const NSInteger kDefaultPrefixAnchor = 0;
static const BOOL kDefaultSortByScore = YES;
static const BOOL kDefaultFilterByScore = YES;
static const BOOL kDefaultShowScores = NO;
static const BOOL kDefaultShowInlinePreview = YES;
static const BOOL kDefaultHideCursorInNonPrefixPreview = NO;
static const BOOL kDefaultShowListHeader = YES;
static const BOOL kDefaultShowNumMatches = NO;
static const BOOL kDefaultNormalizeScores = NO;
static const BOOL kDefaultShowTiming = NO;
static NSString * const kDefaultScoreFormat = @"* #0.00";

static const double kDefaultMatchScorePower = 2.0;
static const double kDefaultPriorityPower = 0.5;
static const double kDefaultPriorityFactorPower = 0.5;
static const double kDefaultMaxPrefixBonus = 0.5;

// experimental

static const BOOL kDefaultCorrectLetterCase = NO;
static const BOOL kDefaultCorrectLetterCaseBestMatchOnly = NO;
static const BOOL kDefaultCorrectWordOrder = NO;
static const NSInteger kDefaultCorrectWordOrderAfter = 2;

- (IBAction)resetDefaults:(id)sender {
    self.pluginEnabled = kDefaultPluginEnabled;

    self.minimumScoreThreshold = kDefaultMinimumScoreThreshold;
    self.filterByScore = kDefaultFilterByScore;
    self.sortByScore = kDefaultSortByScore;
    self.showScores = kDefaultShowScores;
    self.scoreFormat = kDefaultScoreFormat;
    self.normalizeScores = kDefaultNormalizeScores;
    self.showListHeader = kDefaultShowListHeader;
    self.showNumMatches = kDefaultShowNumMatches;
    self.showInlinePreview = kDefaultShowInlinePreview;
    self.hideCursorInNonPrefixPreview = kDefaultHideCursorInNonPrefixPreview;
    self.showTiming = kDefaultShowTiming;
    self.prefixAnchor = kDefaultPrefixAnchor;

    self.matchScorePower = kDefaultMatchScorePower;
    self.priorityPower = kDefaultPriorityPower;
    self.priorityFactorPower = kDefaultPriorityFactorPower;
    self.maxPrefixBonus = kDefaultMaxPrefixBonus;

    self.correctLetterCase = kDefaultCorrectLetterCase;
    self.correctLetterCaseBestMatchOnly = kDefaultCorrectLetterCaseBestMatchOnly;
    self.correctWordOrder = kDefaultCorrectWordOrder;
    self.correctWordOrderAfter = kDefaultCorrectWordOrderAfter;

    NSUInteger processors = [[NSProcessInfo processInfo] activeProcessorCount];
    self.parallelScoring = processors > 1;
    self.maximumWorkers = processors;
}

- (void) loadFromDefaults {
    NSUInteger processors = [[NSProcessInfo processInfo] activeProcessorCount];
    BOOL kDefaultParallelScoring = processors > 1;
    NSInteger kDefaultMaximumWorkers = processors;

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSNumber * number;

#define loadNumber(name, Name) \
    number = [defaults objectForKey: k ## Name ## Key]; \
    [self setValue: number ?: @(kDefault ## Name) forKey: @#name]

    loadNumber(pluginEnabled, PluginEnabled);

    loadNumber(minimumScoreThreshold, MinimumScoreThreshold);
    loadNumber(sortByScore, SortByScore);
    loadNumber(filterByScore, FilterByScore);
    loadNumber(showScores, ShowScores);
    loadNumber(parallelScoring, ParallelScoring);
    loadNumber(maximumWorkers, MaximumWorkers);
    loadNumber(normalizeScores, NormalizeScores);
    loadNumber(showInlinePreview, ShowInlinePreview);
    loadNumber(hideCursorInNonPrefixPreview, HideCursorInNonPrefixPreview);
    loadNumber(showListHeader, ShowListHeader);
    loadNumber(showNumMatches, ShowNumMatches);
    loadNumber(showTiming, ShowTiming);
    loadNumber(prefixAnchor, PrefixAnchor);

    loadNumber(matchScorePower, MatchScorePower);
    loadNumber(priorityPower, PriorityPower);
    loadNumber(priorityFactorPower, PriorityFactorPower);
    loadNumber(maxPrefixBonus, MaxPrefixBonus);

    loadNumber(correctLetterCase, CorrectLetterCase);
    loadNumber(correctLetterCaseBestMatchOnly, CorrectLetterCaseBestMatchOnly);
    loadNumber(correctWordOrder, CorrectWordOrder);
    loadNumber(correctWordOrderAfter, CorrectWordOrderAfter);

#undef loadNumber

    self.scoreFormat = [defaults stringForKey: kScoreFormatKey] ?: kDefaultScoreFormat;

    number = [defaults objectForKey: kSettingsVersionKey];

    if (!number || [number unsignedIntegerValue] < kSettingsVersion) {
        [self migrateSettingsFromVersion: [number unsignedIntegerValue]];
        NSString * pluginName = [NSBundle bundleForClass: self.class].lsl_bundleName;
        [defaults setObject: @(kSettingsVersion) forKey: kSettingsVersionKey];
        NSAlert * alert = [NSAlert alertWithMessageText: [NSString stringWithFormat: @"New settings for %@.", pluginName]
                                          defaultButton: @"View"
                                        alternateButton: @"Skip"
                                            otherButton: nil
                              informativeTextWithFormat: @"New settings are available for %@ plugin. Do you want to review them now?\n\nYou can always access the settings later from the Menu:\nEditor > %@ > Plugin Settings...", pluginName, pluginName];
        if ([alert runModal] == NSAlertDefaultReturn) {
            [self showSettingsWindow];
        }
    }

    [[NSUserDefaults standardUserDefaults] synchronize];

}

# pragma mark - migrate

- (void) migrateSettingsFromVersion:(NSUInteger)version {
    switch (version) {
        case 0: // just break, dont migrate for 0
            break;
        case 1: // dont break, fall through to higher cases
        case 2:
        case 3:
            self.showListHeader = YES;
    }
}

# pragma mark - boilerplate

// use macros to avoid some copy-paste errors

#define SETTINGS_KEY(Name) \
static NSString * const k ## Name ## Key = @"FuzzyAutocomplete"#Name

#define SETTINGS_SETTER(name, Name, type, function) SETTINGS_KEY(Name); \
- (void) set ## Name: (type) name { \
[[NSUserDefaults standardUserDefaults] setObject: function(name) forKey: k ## Name ## Key]; \
_ ## name = name; \
}

#define STRING_SETTINGS_SETTER(name, Name) SETTINGS_SETTER(name, Name, NSString *, (NSString *))
#define NUMBER_SETTINGS_SETTER(name, Name, type) SETTINGS_SETTER(name, Name, type, @)
#define DOUBLE_SETTINGS_SETTER(name, Name) NUMBER_SETTINGS_SETTER(name, Name, double)
#define BOOL_SETTINGS_SETTER(name, Name) NUMBER_SETTINGS_SETTER(name, Name, BOOL)
#define INTEGER_SETTINGS_SETTER(name, Name) NUMBER_SETTINGS_SETTER(name, Name, NSInteger)

SETTINGS_KEY(SettingsVersion);

BOOL_SETTINGS_SETTER(pluginEnabled, PluginEnabled)

BOOL_SETTINGS_SETTER(showScores, ShowScores)
BOOL_SETTINGS_SETTER(filterByScore, FilterByScore)
BOOL_SETTINGS_SETTER(sortByScore, SortByScore)
BOOL_SETTINGS_SETTER(parallelScoring, ParallelScoring)
BOOL_SETTINGS_SETTER(normalizeScores, NormalizeScores)
BOOL_SETTINGS_SETTER(showInlinePreview, ShowInlinePreview)
BOOL_SETTINGS_SETTER(hideCursorInNonPrefixPreview, HideCursorInNonPrefixPreview)
BOOL_SETTINGS_SETTER(showListHeader, ShowListHeader)
BOOL_SETTINGS_SETTER(showNumMatches, ShowNumMatches)
BOOL_SETTINGS_SETTER(showTiming, ShowTiming)
BOOL_SETTINGS_SETTER(correctLetterCase, CorrectLetterCase);
BOOL_SETTINGS_SETTER(correctLetterCaseBestMatchOnly, CorrectLetterCaseBestMatchOnly);
BOOL_SETTINGS_SETTER(correctWordOrder, CorrectWordOrder);

INTEGER_SETTINGS_SETTER(maximumWorkers, MaximumWorkers)
INTEGER_SETTINGS_SETTER(prefixAnchor, PrefixAnchor)
INTEGER_SETTINGS_SETTER(correctWordOrderAfter, CorrectWordOrderAfter);

DOUBLE_SETTINGS_SETTER(minimumScoreThreshold, MinimumScoreThreshold)
DOUBLE_SETTINGS_SETTER(matchScorePower, MatchScorePower)
DOUBLE_SETTINGS_SETTER(priorityPower, PriorityPower)
DOUBLE_SETTINGS_SETTER(priorityFactorPower, PriorityFactorPower)
DOUBLE_SETTINGS_SETTER(maxPrefixBonus, MaxPrefixBonus)

STRING_SETTINGS_SETTER(scoreFormat, ScoreFormat)

@end


text:
package org.springframework.data.simpledb.core.entity;

import org.springframework.data.simpledb.core.entity.json.JsonMarshaller;

import java.io.Serializable;
import java.lang.reflect.Field;

public class JSONFieldWrapper <T, ID extends Serializable> extends AbstractSimpleFieldWrapper<T, ID> {

    public JSONFieldWrapper(Field field, EntityWrapper<T, ID> parent, final boolean isNewParent) {
        super(field, parent, isNewParent);
    }

    @Override
    public String serializeValue() {
        if(getFieldValue() != null) {
            return JsonMarshaller.getInstance().marshall(getFieldValue());
        }

        return null;
    }

    @Override
    public Object deserializeValue(String value) {
        Object ret = null;

        if(value != null) {
            ret = JsonMarshaller.getInstance().unmarshall(value, getField().getType());
        }

        return ret;
    }
}


text:
package com.hp.ov.sdk.storage;

import java.util.Map;

import com.hp.ov.sdk.dto.Patch;
import com.hp.ov.sdk.dto.Patch.PatchOperation;
import com.hp.ov.sdk.dto.RefreshState;
import com.hp.ov.sdk.dto.storage.driveenclosures.DriveEnclosure;
import com.hp.ov.sdk.dto.storage.driveenclosures.DriveEnclosureRefreshRequest;
import com.hp.ov.sdk.exceptions.SDKResourceNotFoundException;
import com.hp.ov.sdk.oneview.BasicResource;
import com.hp.ov.sdk.oneview.PatchResource;
import com.hp.ov.sdk.oneview.Resource;
import com.hp.ov.sdk.oneview.UpdateResource;
import com.hp.ov.sdk.rest.client.storage.DriveEnclosureClient;

public class DriveEnclosureResource extends BasicResource implements Resource, UpdateResource, PatchResource {

    private static DriveEnclosureResource instance;

    private DriveEnclosureClient client;

    public DriveEnclosureResource() {
        client = oneViewClient.driveEnclosure();
    }

    public static DriveEnclosureResource getInstance() {
        if (instance == null) {
            instance = new DriveEnclosureResource();
        }
        return instance;
    }

    @Override
    public Map<String, String> getResourceProperties(String id) {
        return getResourceProperties(client.getById(id));
    }

    @Override
    public String findByName(String name) {
        DriveEnclosure driveEnclosure = (DriveEnclosure) getResource(client.getByName(name));
        return driveEnclosure == null ? "" : driveEnclosure.getResourceId();
    }

    @Override
    public String findById(String id) {
        try {
            return client.getById(id).getName();
        } catch (final SDKResourceNotFoundException ex) {
            return "";
        }
    }

    @Override
    public int count() {
        return getCount(client.getAll());
    }

    @Override
    public String update(String id) {
        DriveEnclosureRefreshRequest refresh = new DriveEnclosureRefreshRequest();
        refresh.setRefreshState(RefreshState.valueOf(resourceProperties.get("refreshState")));
        return taskToString(client.updateRefreshState(id, refresh));
    }

    public String getPortMap(String id) {
        return objToString(client.getPortMap(id));
    }

    @Override
    public String patch(String id) {
        return taskToString(client.patch(id, buildPatch(id)));
    }

    public Patch buildPatch(String id) {
        Patch patch = new Patch();
        patch.setOp(PatchOperation.valueOf(resourceProperties.get("op")));
        patch.setPath(resourceProperties.get("path"));
        patch.setValue(resourceProperties.get("value"));
        return patch;
    }

}


text:
# encoding: utf-8
# frozen_string_literal: true

require 'spec_helper'

describe RuboCop::ConfigLoader do
  include FileHelper

  let(:default_config) { described_class.default_configuration }

  describe '.configuration_file_for', :isolated_environment do
    subject(:configuration_file_for) do
      described_class.configuration_file_for(dir_path)
    end

    context 'when no config file exists in ancestor directories' do
      let(:dir_path) { 'dir' }
      before { create_file('dir/example.rb', '') }

      context 'but a config file exists in home directory' do
        before { create_file('~/.rubocop.yml', '') }

        it 'returns the path to the file in home directory' do
          expect(configuration_file_for).to end_with('home/.rubocop.yml')
        end
      end

      context 'and no config file exists in home directory' do
        it 'falls back to the provided default file' do
          expect(configuration_file_for).to end_with('config/default.yml')
        end
      end

      context 'and ENV has no `HOME` defined' do
        before { ENV.delete 'HOME' }

        it 'falls back to the provided default file' do
          expect(configuration_file_for).to end_with('config/default.yml')
        end
      end
    end

    context 'when a config file exists in the parent directory' do
      let(:dir_path) { 'dir' }

      before do
        create_file('dir/example.rb', '')
        create_file('.rubocop.yml', '')
      end

      it 'returns the path to that configuration file' do
        expect(configuration_file_for).to end_with('work/.rubocop.yml')
      end
    end

    context 'when multiple config files exist in ancestor directories' do
      let(:dir_path) { 'dir' }

      before do
        create_file('dir/example.rb', '')
        create_file('dir/.rubocop.yml', '')
        create_file('.rubocop.yml', '')
      end

      it 'prefers closer config file' do
        expect(configuration_file_for).to end_with('dir/.rubocop.yml')
      end
    end
  end

  describe '.configuration_from_file', :isolated_environment do
    subject(:configuration_from_file) do
      described_class.configuration_from_file(file_path)
    end

    context 'with any config file' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file(file_path, ['Style/Encoding:',
                                '  Enabled: false'])
      end

      it 'returns a configuration inheriting from default.yml' do
        config = default_config['Style/Encoding'].dup
        config['Enabled'] = false
        expect(configuration_from_file.to_h)
          .to eql(default_config.merge('Style/Encoding' => config))
      end
    end

    context 'when multiple config files exist in ancestor directories' do
      let(:file_path) { 'dir/.rubocop.yml' }

      before do
        create_file('.rubocop.yml',
                    ['AllCops:',
                     '  Exclude:',
                     '    - vendor/**'])

        create_file(file_path,
                    ['AllCops:',
                     '  Exclude: []'])
      end

      it 'gets AllCops/Exclude from the highest directory level' do
        excludes = configuration_from_file['AllCops']['Exclude']
        expect(excludes).to eq([File.expand_path('vendor/**')])
      end
    end

    context 'when a file inherits from a parent file' do
      let(:file_path) { 'dir/.rubocop.yml' }

      before do
        create_file('.rubocop.yml',
                    ['AllCops:',
                     '  Exclude:',
                     '    - vendor/**',
                     '    - !ruby/regexp /[A-Z]/'])

        create_file(file_path, ['inherit_from: ../.rubocop.yml'])
      end

      it 'gets an absolute AllCops/Exclude' do
        excludes = configuration_from_file['AllCops']['Exclude']
        expect(excludes).to eq([File.expand_path('vendor/**'), /[A-Z]/])
      end
    end

    context 'when a file inherits from an empty parent file' do
      let(:file_path) { 'dir/.rubocop.yml' }

      before do
        create_file('.rubocop.yml', [''])

        create_file(file_path, ['inherit_from: ../.rubocop.yml'])
      end

      it 'does not fail to load' do
        expect { configuration_from_file }.not_to raise_error
      end
    end

    context 'when a file inherits from a sibling file' do
      let(:file_path) { 'dir/.rubocop.yml' }

      before do
        create_file('src/.rubocop.yml',
                    ['AllCops:',
                     '  Exclude:',
                     '    - vendor/**'])

        create_file(file_path, ['inherit_from: ../src/.rubocop.yml'])
      end

      it 'gets an absolute AllCops/Exclude' do
        excludes = configuration_from_file['AllCops']['Exclude']
        expect(excludes).to eq([File.expand_path('src/vendor/**')])
      end
    end

    context 'when a file inherits from a parent and grandparent file' do
      let(:file_path) { 'dir/subdir/.rubocop.yml' }

      before do
        create_file('dir/subdir/example.rb', '')

        create_file('.rubocop.yml',
                    ['Metrics/LineLength:',
                     '  Enabled: false',
                     '  Max: 77'])

        create_file('dir/.rubocop.yml',
                    ['inherit_from: ../.rubocop.yml',
                     '',
                     'Metrics/MethodLength:',
                     '  Enabled: true',
                     '  CountComments: false',
                     '  Max: 10'])

        create_file(file_path,
                    ['inherit_from: ../.rubocop.yml',
                     '',
                     'Metrics/LineLength:',
                     '  Enabled: true',
                     '',
                     'Metrics/MethodLength:',
                     '  Max: 5'])
      end

      it 'returns the ancestor configuration plus local overrides' do
        config =
          default_config.merge(
            'Metrics/LineLength' => {
              'Description' =>
              default_config['Metrics/LineLength']['Description'],
              'StyleGuide' => '#80-character-limits',
              'Enabled' => true,
              'Max' => 77,
              'AllowHeredoc' => true,
              'AllowURI' => true,
              'URISchemes' => %w(http https)
            },
            'Metrics/MethodLength' => {
              'Description' =>
              default_config['Metrics/MethodLength']['Description'],
              'StyleGuide' => '#short-methods',
              'Enabled' => true,
              'CountComments' => false,
              'Max' => 5
            }
          )
        expect(configuration_from_file.to_h).to eq(config)
      end
    end

    context 'when a file inherits from two configurations' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file('example.rb', '')

        create_file('normal.yml',
                    ['Metrics/MethodLength:',
                     '  Enabled: false',
                     '  CountComments: true',
                     '  Max: 80'])

        create_file('special.yml',
                    ['Metrics/MethodLength:',
                     '  Enabled: false',
                     '  Max: 200'])

        create_file(file_path,
                    ['inherit_from:',
                     '  - normal.yml',
                     '  - special.yml',
                     '',
                     'Metrics/MethodLength:',
                     '  Enabled: true'])
      end

      it 'returns values from the last one when possible' do
        expected = { 'Enabled' => true,        # overridden in .rubocop.yml
                     'CountComments' => true,  # only defined in normal.yml
                     'Max' => 200 }            # special.yml takes precedence
        expect(configuration_from_file['Metrics/MethodLength'].to_set)
          .to be_superset(expected.to_set)
      end
    end

    context 'when a file inherits and overrides with non-namedspaced cops' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file('example.rb', '')

        create_file('line_length.yml',
                    ['LineLength:',
                     '  Max: 120'])

        create_file(file_path,
                    ['inherit_from:',
                     '  - line_length.yml',
                     '',
                     'LineLength:',
                     '  AllowHeredoc: false'])
      end

      it 'returns includes both of the cop changes' do
        config =
          default_config.merge(
            'Metrics/LineLength' => {
              'Description' =>
              default_config['Metrics/LineLength']['Description'],
              'StyleGuide' => '#80-character-limits',
              'Enabled' => true,
              'Max' => 120,             # overridden in line_length.yml
              'AllowHeredoc' => false,  # overridden in rubocop.yml
              'AllowURI' => true,
              'URISchemes' => %w(http https)
            }
          )

        expect(configuration_from_file.to_h).to eq(config)
      end
    end

    context 'when a file inherits from an expanded path' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file('~/.rubocop.yml', [''])
        create_file(file_path, ['inherit_from: ~/.rubocop.yml'])
      end

      it 'does not fail to load expanded path' do
        expect { configuration_from_file }.not_to raise_error
      end
    end

    context 'when a file inherits from an unknown gem' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file(file_path,
                    ['inherit_gem:',
                     '  not_a_real_gem: config/rubocop.yml'])
      end

      it 'fails to load' do
        expect { configuration_from_file }.to raise_error(Gem::LoadError)
      end
    end

    context 'when a file inherits from the rubocop gem' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file(file_path,
                    ['inherit_gem:',
                     '  rubocop: config/default.yml'])
      end

      it 'fails to load' do
        expect { configuration_from_file }.to raise_error(ArgumentError)
      end
    end

    context 'when a file inherits from a known gem' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file('gemone/config/rubocop.yml',
                    ['Metrics/MethodLength:',
                     '  Enabled: false',
                     '  Max: 200',
                     '  CountComments: false'])
        create_file('gemtwo/config/default.yml',
                    ['Metrics/LineLength:',
                     '  Enabled: true'])
        create_file('gemtwo/config/strict.yml',
                    ['Metrics/LineLength:',
                     '  Max: 72',
                     '  AllowHeredoc: false'])
        create_file('local.yml',
                    ['Metrics/MethodLength:',
                     '  CountComments: true'])
        create_file(file_path,
                    ['inherit_gem:',
                     '  gemone: config/rubocop.yml',
                     '  gemtwo:',
                     '    - config/default.yml',
                     '    - config/strict.yml',
                     '',
                     'inherit_from: local.yml',
                     '',
                     'Metrics/MethodLength:',
                     '  Enabled: true',
                     '',
                     'Metrics/LineLength:',
                     '  AllowURI: false'])
      end

      it 'returns values from the gem config with local overrides' do
        gem_class = Struct.new(:gem_dir)
        %w(gemone gemtwo).each do |gem_name|
          mock_spec = gem_class.new(gem_name)
          expect(Gem::Specification).to receive(:find_by_name)
            .at_least(:once).with(gem_name).and_return(mock_spec)
        end

        expected = { 'Enabled' => true,        # overridden in .rubocop.yml
                     'CountComments' => true,  # overridden in local.yml
                     'Max' => 200 }            # inherited from somegem
        expect(configuration_from_file['Metrics/MethodLength'].to_set)
          .to be_superset(expected.to_set)

        expected = { 'Enabled' => true,        # gemtwo/config/default.yml
                     'Max' => 72,              # gemtwo/config/strict.yml
                     'AllowHeredoc' => false,  # gemtwo/config/strict.yml
                     'AllowURI' => false }     # overridden in .rubocop.yml
        expect(configuration_from_file['Metrics/LineLength'].to_set)
          .to be_superset(expected.to_set)
      end
    end

    context 'when a file inherits from a url' do
      let(:file_path) { '.rubocop.yml' }
      let(:cache_file) { '.rubocop-http---example-com-rubocop-yml' }

      before do
        stub_request(:get, /example.com/)
          .to_return(status: 200, body: "Style/Encoding:\n    Enabled: true")

        create_file(file_path, ['inherit_from: http://example.com/rubocop.yml'])
      end

      after do
        File.unlink cache_file if File.exist? cache_file
      end

      it 'creates the cached file alongside the owning file' do
        configuration_from_file
        expect(File.exist?(cache_file)).to be true
      end
    end

    context 'when a file inherits from a non http/https url' do
      let(:file_path) { '.rubocop.yml' }

      before do
        create_file(file_path, ['inherit_from: c:\\\\foo\\bar.yml'])
      end

      it 'fails to load the resulting path' do
        expect { configuration_from_file }.to raise_error(Errno::ENOENT)
      end
    end
  end

  describe '.load_file', :isolated_environment do
    subject(:load_file) do
      described_class.load_file(configuration_path)
    end

    let(:configuration_path) { '.rubocop.yml' }

    it 'returns a configuration loaded from the passed path' do
      create_file(configuration_path, [
                    'Style/Encoding:',
                    '  Enabled: true'
                  ])
      configuration = load_file
      expect(configuration['Style/Encoding']).to eq(
        'Enabled' => true
      )
    end

    it 'fails with a TypeError when loading a malformed configuration file' do
      create_file(configuration_path, 'This string is not a YAML hash')
      expect { load_file }.to raise_error(
        TypeError, /^Malformed configuration in .*\.rubocop\.yml$/
      )
    end

    it 'loads configuration properly when it includes non-ascii characters ' do
      create_file(configuration_path, ['# All these cops of mine are ❤',
                                       'Style/Encoding:',
                                       '  Enabled: false'])

      expect(load_file.to_h).to eq('Style/Encoding' => { 'Enabled' => false })
    end

    it 'returns an empty configuration loaded from an empty file' do
      create_file(configuration_path, '')
      configuration = load_file
      expect(configuration.to_h).to eq({})
    end

    context 'when SafeYAML is required' do
      before do
        create_file(configuration_path, [
                      'Style/WordArray:',
                      "  WordRegex: !ruby/regexp '/\\A[\\p{Word}]+\\z/'"
                    ])
      end

      context 'when it is fully required' do
        it 'de-serializes Regexp class' do
          in_its_own_process_with('safe_yaml') do
            configuration = described_class.load_file('.rubocop.yml')

            word_regexp = configuration['Style/WordArray']['WordRegex']
            expect(word_regexp).to be_a(::Regexp)
          end
        end
      end

      context 'when safe_yaml is required without monkey patching' do
        it 'de-serializes Regexp class' do
          in_its_own_process_with('safe_yaml/load') do
            configuration = described_class.load_file('.rubocop.yml')

            word_regexp = configuration['Style/WordArray']['WordRegex']
            expect(word_regexp).to be_a(::Regexp)
          end
        end

        context 'and SafeYAML.load is private' do
          # According to issue #2935, SafeYAML.load can be private in some
          # circumstances.
          it 'does not raise private method load called for SafeYAML:Module' do
            in_its_own_process_with('safe_yaml/load') do
              SafeYAML.send :private_class_method, :load
              configuration = described_class.load_file('.rubocop.yml')

              word_regexp = configuration['Style/WordArray']['WordRegex']
              expect(word_regexp).to be_a(::Regexp)
            end
          end
        end
      end
    end
  end

  describe '.merge' do
    subject(:merge) { described_class.merge(base, derived) }

    let(:base) do
      {
        'AllCops' => {
          'Include' => ['**/*.gemspec', '**/Rakefile'],
          'Exclude' => []
        }
      }
    end
    let(:derived) do
      { 'AllCops' => { 'Exclude' => ['example.rb', 'exclude_*'] } }
    end

    it 'returns a recursive merge of its two arguments' do
      expect(merge).to eq('AllCops' => {
                            'Include' => ['**/*.gemspec', '**/Rakefile'],
                            'Exclude' => ['example.rb', 'exclude_*']
                          })
    end
  end

  describe 'configuration for SymbolArray', :isolated_environment do
    let(:config) do
      config_path = described_class.configuration_file_for('.')
      described_class.configuration_from_file(config_path)
    end

    context 'when no config file exists for the target file' do
      it 'is disabled' do
        expect(
          config.cop_enabled?(RuboCop::Cop::Style::SymbolArray)
        ).to be_falsey
      end
    end

    context 'when a config file which does not mention SymbolArray exists' do
      it 'is disabled' do
        create_file('.rubocop.yml', [
                      'Metrics/LineLength:',
                      '  Max: 80'
                    ])
        expect(
          config.cop_enabled?(RuboCop::Cop::Style::SymbolArray)
        ).to be_falsey
      end
    end

    context 'when a config file which explicitly enables SymbolArray exists' do
      it 'is enabled' do
        create_file('.rubocop.yml', [
                      'Style/SymbolArray:',
                      '  Enabled: true'
                    ])
        expect(
          config.cop_enabled?(RuboCop::Cop::Style::SymbolArray)
        ).to be_truthy
      end
    end
  end

  describe 'configuration for AssignmentInCondition' do
    describe 'AllowSafeAssignment' do
      it 'is enabled by default' do
        default_config = described_class.default_configuration
        symbol_name_config =
          default_config.for_cop('Lint/AssignmentInCondition')
        expect(symbol_name_config['AllowSafeAssignment']).to be_truthy
      end
    end
  end

  describe 'when a requirement is defined', :isolated_environment do
    let(:required_file_path) { './required_file.rb' }

    before do
      create_file('.rubocop.yml', ['require:', "  - #{required_file_path}"])
      create_file(required_file_path, ['class MyClass', 'end'])
    end

    it 'requires the passed path' do
      config_path = described_class.configuration_file_for('.')
      described_class.configuration_from_file(config_path)
      expect(defined?(MyClass)).to be_truthy
    end

    it 'uses paths relative to the .rubocop.yml, not cwd' do
      config_path = described_class.configuration_file_for('.')
      Dir.chdir '..' do
        described_class.configuration_from_file(config_path)
        expect(defined?(MyClass)).to be_truthy
      end
    end
  end

  describe 'when a unqualified requirement is defined', :isolated_environment do
    let(:required_file_path) { 'required_file' }

    before do
      create_file('.rubocop.yml', ['require:', "  - #{required_file_path}"])
      create_file(required_file_path + '.rb', ['class MyClass', 'end'])
    end

    it 'works without a starting .' do
      config_path = described_class.configuration_file_for('.')
      $LOAD_PATH.unshift(File.dirname(config_path))
      Dir.chdir '..' do
        described_class.configuration_from_file(config_path)
        expect(defined?(MyClass)).to be_truthy
      end
    end
  end
end


text:
<?php

/**
 * Returns the current year from the server
 * @return bool|string
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_current_year() {
	return date("Y");
}

/**
 * Returns the name of the WordPress site as stored in the database
 * @return string
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_site_title() {
	return get_bloginfo("name");
}

/**
 * Returns the URL to WordPress site
 * @return string|void
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_site_url() {
	return get_bloginfo("url");
}

/**
 * Returns the URL of the WordPress site
 * @return string|void
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_wp_url() {
	return get_bloginfo("wpurl");
}

/**
 * Returns the template URL
 * @return string|void
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_theme_url() {
	return get_bloginfo("template_url");
}

/**
 * Returns the login URL
 * @return string
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_login_url() {
	return wp_login_url();
}

/**
 * Returns the logout URL
 * @return string
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_logout_url() {
	return wp_logout_url();
}

/**
 * Returns the site tagline
 * @return string|void
 * @version 1.0
 * @since 1.0
 */
function skeleton_wp_sc_site_tagline() {
	return get_bloginfo("description");
}

// TODO: Add date shortcode and allow user to enter in custom format if they wish
function skeleton_wp_sc_date($atts) {
	return $atts;
}

function skeleton_wp_sc_instagram_gallery($atts) {
	return null;
}

add_shortcode("wp-url", "skeleton_wp_sc_wp_url");
add_shortcode("theme-url", "skeleton_wp_sc_theme_url");
add_shortcode("login-url", "skeleton_wp_sc_login_url");
add_shortcode("logout-url", "skeleton_wp_sc_logout_url");
add_shortcode("site-tagline", "skeleton_wp_sc_site_tagline");
add_shortcode("current-year", "skeleton_wp_sc_current_year");
add_shortcode("site-title", "skeleton_wp_sc_site_title");
add_shortcode("instagram-gallery", "skeleton_wp_sc_site_title");
add_shortcode("insta-gallery", "skeleton_wp_sc_site_title");


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

namespace Spring.Mvc4QuickStart.Controllers
{
    public class SuffixNestedController : ApiController
    {
       //same public API as SuffixController, only here so that its config can be shown to
       // be properly read out of a separate 'child' config file

        public string Suffix { get; set; }

        // GET /api/suffixnested
        public IEnumerable<string> Get()
        {
            return new string[] { string.Format("value1_{0}", Suffix), string.Format("value2_{0}", Suffix) };
        }

        // GET /api/suffixnested/5
        public string Get(int id)
        {
            return string.Format("value{0}_{1}", Suffix, id);
        }

        // POST /api/suffixnested
        public void Post(string value)
        {
        }

        // PUT /api/suffixnested/5
        public void Put(int id, string value)
        {
        }

        // DELETE /api/suffixnested/5
        public void Delete(int id)
        {
        }
    }

}


text: zoo.bar{display:block}


text:
module.exports = {
  up: {
    usage: 'up(steps)',
    description: 'Move up `steps` squares.',
    args: [{
      name: 'steps',
      type: 'number',
      default: 1,
      description: 'The number of steps up to move the toucan.'
    }]
  },
  left: {
    usage: 'left(steps)',
    description: 'Move left `steps` squares.',
    args: [{
      name: 'steps',
      type: 'number',
      default: 1,
      description: 'The number of steps left to move the toucan.'
    }]
  },
  right: {
    usage: 'right(steps)',
    description: 'Move right `steps` squares.',
    args: [{
      name: 'steps',
      type: 'number',
      default: 1,
      description: 'The number of steps right to move the toucan.'
    }]
  },
  down: {
    usage: 'down(steps)',
    description: 'Move down `steps` squares.',
    args: [{
      name: 'steps',
      type: 'number',
      default: 1,
      description: 'The number of steps down to move the toucan.'
    }]
  },
  move: {
    usage: 'move()',
    description: 'Move your cursor in whatever direction it is facing.'
  },
  turnRight: {
    usage: 'turnRight()',
    description: 'Turn right 90 degrees.'
  },
  turnLeft: {
    usage: 'turnLeft()',
    description: 'Turn left 90 degrees.'
  },
  paint: {
    usage: 'paint(color)',
    description: 'Paint the square you are currently on `color`.',
    args: [{
      name: 'color',
      type: 'string',
      default: 'black',
      description: 'The color to paint.'
    }]
  },
  repeat: {
    usage: 'repeat(n, function(){\n\t// code to repeat\n})',
    description: 'Repeat the actions inside of the loop.',
    args: [{
      name: 'num',
      type: 'number',
      default: 2,
      description: 'The number of times to repeat the loop.'
    },
    {
      name: 'fn',
      type: 'function',
      description: 'The function to be repeated'
    }]
  },
  repeat_end: {
    description: 'end of a repeat block',
    hidden: true,
    unselectable: true
  },
  rand: {
    usage: 'rand(min, max)',
    description: 'Generate a random number',
    args: [{
      name: 'min',
      type: 'number',
      default: 0,
      description: 'The minimum for the random number'
    },
    {
      name: 'max',
      type: 'number',
    }]
  }
}


text:
#import <Foundation/Foundation.h>

#import <FirebaseFirestore/FIRFirestore.h>

#include <memory>

#include "Firestore/core/src/util/async_queue.h"

NS_ASSUME_NONNULL_BEGIN

@interface FIRFirestore (Testing)

- (const std::shared_ptr<firebase::firestore::util::AsyncQueue> &)workerQueue;

@end

NS_ASSUME_NONNULL_END


text:
<title>
The harsh reality for working New Yorkers
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Thousands line up for 200 jobs at Manhattan candy store

The harsh reality for working New Yorkers

By Hannah Wolfe | November 10, 2006 | Page 2

TWO RECENT incidents in New York City and nearby New Jersey expose the reality behind the happy talk about the U.S. economy from politicians and the media.

On November 3, more than 5,000 people turned up in Times Square in Manhattan in response to an ad for 200 jobs--only 65 of them full-time--at an M&Ms World candy store. The ad promised $10.75 hourly pay--well above the $6.75 an hour minimum wage, though far from a living wage in New York City--full benefits and "on-the spot-hiring."

Applicants traveled from miles around and began arriving as early as 1 a.m. When the crowd became so large that traffic was disrupted, mounted police were called in to "control" the crowd.

"This is what unemployment looks like in New York City," said 28-year-old Tamika Jones, a mother of three, "I wanted to cry."

Three weeks earlier, an eerily similar event unfolded in New Jersey when 2,000 people flooded the housing authority headquarters in the city of Orange to get 200 applications for vouchers that subsidize rent for low-income families. When the crowd became "unruly," according to reports, police were called in and pepper-gassed the crowd.

New Jersey is the most expensive state for homeowners and third-most expensive state for renters, according to the Census Bureau. An estimated 38 percent of New Jersey homeowners and 47 percent of tenants spend more than 30 percent of their income on housing costs.

"It shows you the state of the economy when this many people show up because they are in dire need of housing assistance," Karen Patton, a 48-year-old mother of three, told the New Jersey Star-Ledger. Patton, who has a full-time job, lined up for an application, but left when the cops moved in, because, she said, "it's more important for me to be alive than be crushed to death to get an application."

Arnold Cohen, policy coordinator for the Housing and Community Development Network of New Jersey, told the Star-Ledger, "For people of lower incomes, the situation is desperate. There is no housing that addresses their needs except for public housing or Section 8. Otherwise, people have nowhere to turn."

A report issued by Cohen's group earlier this year said average rent for a two-bedroom apartment in New Jersey is $1,085 a month, and 53 percent of renters can't afford the cost.

Karen Patton is spending $951 on a three-bedroom apartment in Orange while earning below the Section 8 threshold of $42,200. "I do what I can do," she said. "But add utilities, gas to go to work and insurance, and it's hard to make ends meet. The state of the economy is not what people make it out to be."

Reminiscent of the bread lines of the Great Depression of the 1930s, these two incidents point to the harsh disconnect between publicized statistics showing an economic recovery--and what life is really like for lower-income working people.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
import math
import operator
from llvmlite import ir
from numba.core import types, typing, utils, cgutils
from numba.core.imputils import Registry
from numba.types import float32, float64, int64, uint64
from numba.cuda import libdevice

registry = Registry()
lower = registry.lower

booleans = []
booleans += [('isnand', 'isnanf', math.isnan)]
booleans += [('isinfd', 'isinff', math.isinf)]
booleans += [('isfinited', 'finitef', math.isfinite)]

unarys = []
unarys += [('ceil', 'ceilf', math.ceil)]
unarys += [('floor', 'floorf', math.floor)]
unarys += [('fabs', 'fabsf', math.fabs)]
unarys += [('exp', 'expf', math.exp)]
unarys += [('expm1', 'expm1f', math.expm1)]
unarys += [('erf', 'erff', math.erf)]
unarys += [('erfc', 'erfcf', math.erfc)]
unarys += [('tgamma', 'tgammaf', math.gamma)]
unarys += [('lgamma', 'lgammaf', math.lgamma)]
unarys += [('sqrt', 'sqrtf', math.sqrt)]
unarys += [('log', 'logf', math.log)]
unarys += [('log2', 'log2f', math.log2)]
unarys += [('log10', 'log10f', math.log10)]
unarys += [('log1p', 'log1pf', math.log1p)]
unarys += [('acosh', 'acoshf', math.acosh)]
unarys += [('acos', 'acosf', math.acos)]
unarys += [('cos', 'cosf', math.cos)]
unarys += [('cosh', 'coshf', math.cosh)]
unarys += [('asinh', 'asinhf', math.asinh)]
unarys += [('asin', 'asinf', math.asin)]
unarys += [('sin', 'sinf', math.sin)]
unarys += [('sinh', 'sinhf', math.sinh)]
unarys += [('atan', 'atanf', math.atan)]
unarys += [('atanh', 'atanhf', math.atanh)]
unarys += [('tan', 'tanf', math.tan)]
unarys += [('tanh', 'tanhf', math.tanh)]

unarys_fastmath = {}
unarys_fastmath['cosf'] = 'fast_cosf'
unarys_fastmath['sinf'] = 'fast_sinf'
unarys_fastmath['tanf'] = 'fast_tanf'
unarys_fastmath['expf'] = 'fast_expf'
unarys_fastmath['log2f'] = 'fast_log2f'
unarys_fastmath['log10f'] = 'fast_log10f'
unarys_fastmath['logf'] = 'fast_logf'

binarys = []
binarys += [('copysign', 'copysignf', math.copysign)]
binarys += [('atan2', 'atan2f', math.atan2)]
binarys += [('pow', 'powf', math.pow)]
binarys += [('fmod', 'fmodf', math.fmod)]
binarys += [('hypot', 'hypotf', math.hypot)]
if utils.PYVERSION >= (3, 7):
    binarys += [('remainder', 'remainderf', math.remainder)]

binarys_fastmath = {}
binarys_fastmath['powf'] = 'fast_powf'

@lower(math.isinf, types.Integer)
@lower(math.isnan, types.Integer)
def math_isinf_isnan_int(context, builder, sig, args):
    return context.get_constant(types.boolean, 0)

@lower(operator.truediv, types.float32, types.float32)
def maybe_fast_truediv(context, builder, sig, args):
    if context.fastmath:
        sig = typing.signature(float32, float32, float32)
        impl = context.get_function(libdevice.fast_fdividef, sig)
        return impl(builder, args)
    else:
        with cgutils.if_zero(builder, args[1]):
            context.error_model.fp_zero_division(builder, ("division by zero",))
        res = builder.fdiv(*args)
        return res

@lower(math.isfinite, types.Integer)
def math_isfinite_int(context, builder, sig, args):
    return context.get_constant(types.boolean, 1)

def impl_boolean(key, ty, libfunc):
    def lower_boolean_impl(context, builder, sig, args):
        libfunc_impl = context.get_function(libfunc,
                                            typing.signature(types.int32, ty))
        result = libfunc_impl(builder, args)
        return context.cast(builder, result, types.int32, types.boolean)

    lower(key, ty)(lower_boolean_impl)

def impl_unary(key, ty, libfunc):
    def lower_unary_impl(context, builder, sig, args):
        actual_libfunc = libfunc
        fast_replacement = None
        if ty == float32 and context.fastmath:
            fast_replacement = unarys_fastmath.get(libfunc.__name__)

        if fast_replacement is not None:
            actual_libfunc = getattr(libdevice, fast_replacement)

        libfunc_impl = context.get_function(actual_libfunc,
                                            typing.signature(ty, ty))
        return libfunc_impl(builder, args)

    lower(key, ty)(lower_unary_impl)

def impl_unary_int(key, ty, libfunc):
    def lower_unary_int_impl(context, builder, sig, args):
        if sig.args[0] == int64:
            convert = builder.sitofp
        elif sig.args[0] == uint64:
            convert = builder.uitofp
        else:
            m = 'Only 64-bit integers are supported for generic unary int ops'
            raise TypeError(m)

        arg = convert(args[0], ir.DoubleType())
        sig = typing.signature(float64, float64)
        libfunc_impl = context.get_function(libfunc, sig)
        return libfunc_impl(builder, [arg])

    lower(key, ty)(lower_unary_int_impl)

def impl_binary(key, ty, libfunc):
    def lower_binary_impl(context, builder, sig, args):
        actual_libfunc = libfunc
        fast_replacement = None
        if ty == float32 and context.fastmath:
            fast_replacement = binarys_fastmath.get(libfunc.__name__)

        if fast_replacement is not None:
            actual_libfunc = getattr(libdevice, fast_replacement)

        libfunc_impl = context.get_function(actual_libfunc,
                                            typing.signature(ty, ty, ty))
        return libfunc_impl(builder, args)

    lower(key, ty, ty)(lower_binary_impl)

def impl_binary_int(key, ty, libfunc):
    def lower_binary_int_impl(context, builder, sig, args):
        if sig.args[0] == int64:
            convert = builder.sitofp
        elif sig.args[0] == uint64:
            convert = builder.uitofp
        else:
            m = 'Only 64-bit integers are supported for generic binary int ops'
            raise TypeError(m)

        args = [convert(arg, ir.DoubleType()) for arg in args]
        sig = typing.signature(float64, float64, float64)
        libfunc_impl = context.get_function(libfunc, sig)
        return libfunc_impl(builder, args)

    lower(key, ty, ty)(lower_binary_int_impl)

for fname64, fname32, key in booleans:
    impl32 = getattr(libdevice, fname32)
    impl64 = getattr(libdevice, fname64)
    impl_boolean(key, float32, impl32)
    impl_boolean(key, float64, impl64)

for fname64, fname32, key in unarys:
    impl32 = getattr(libdevice, fname32)
    impl64 = getattr(libdevice, fname64)
    impl_unary(key, float32, impl32)
    impl_unary(key, float64, impl64)
    impl_unary_int(key, int64, impl64)
    impl_unary_int(key, uint64, impl64)

for fname64, fname32, key in binarys:
    impl32 = getattr(libdevice, fname32)
    impl64 = getattr(libdevice, fname64)
    impl_binary(key, float32, impl32)
    impl_binary(key, float64, impl64)
    impl_binary_int(key, int64, impl64)
    impl_binary_int(key, uint64, impl64)

def impl_pow_int(ty, libfunc):
    def lower_pow_impl_int(context, builder, sig, args):
        powi_sig = typing.signature(ty, ty, types.int32)
        libfunc_impl = context.get_function(libfunc, powi_sig)
        return libfunc_impl(builder, args)

    lower(math.pow, ty, types.int32)(lower_pow_impl_int)

impl_pow_int(types.float32, libdevice.powif)
impl_pow_int(types.float64, libdevice.powi)

def impl_modf(ty, libfunc):
    retty = types.UniTuple(ty, 2)

    def lower_modf_impl(context, builder, sig, args):
        modf_sig = typing.signature(retty, ty)
        libfunc_impl = context.get_function(libfunc, modf_sig)
        return libfunc_impl(builder, args)

    lower(math.modf, ty)(lower_modf_impl)

impl_modf(types.float32, libdevice.modff)
impl_modf(types.float64, libdevice.modf)

def impl_frexp(ty, libfunc):
    retty = types.Tuple((ty, types.int32))

    def lower_frexp_impl(context, builder, sig, args):
        frexp_sig = typing.signature(retty, ty)
        libfunc_impl = context.get_function(libfunc, frexp_sig)
        return libfunc_impl(builder, args)

    lower(math.frexp, ty)(lower_frexp_impl)

impl_frexp(types.float32, libdevice.frexpf)
impl_frexp(types.float64, libdevice.frexp)

def impl_ldexp(ty, libfunc):
    def lower_ldexp_impl(context, builder, sig, args):
        ldexp_sig = typing.signature(ty, ty, types.int32)
        libfunc_impl = context.get_function(libfunc, ldexp_sig)
        return libfunc_impl(builder, args)

    lower(math.ldexp, ty, types.int32)(lower_ldexp_impl)

impl_ldexp(types.float32, libdevice.ldexpf)
impl_ldexp(types.float64, libdevice.ldexp)

# Complex power implementations - translations of _Py_c_pow from CPython
# https://github.com/python/cpython/blob/a755410e054e1e2390de5830befc08fe80706c66/Objects/complexobject.c#L123-L151
#
# The complex64 variant casts all constants and some variables to ensure that
# as much computation is done in single precision as possible. A small number
# of operations are still done in 64-bit, but these come from libdevice code.

def cpow_implement(fty, cty):
    def core(context, builder, sig, args):
        def cpow_internal(a, b):

            if b.real == fty(0.0) and b.imag == fty(0.0):
                return cty(1.0) + cty(0.0j)
            elif a.real == fty(0.0) and b.real == fty(0.0):
                return cty(0.0) + cty(0.0j)

            vabs = math.hypot(a.real, a.imag)
            len = math.pow(vabs, b.real)
            at = math.atan2(a.imag, a.real)
            phase = at * b.real
            if b.imag != fty(0.0):
                len /= math.exp(at * b.imag)
                phase += b.imag * math.log(vabs)

            return len * (cty(math.cos(phase)) +
                          cty(math.sin(phase) * cty(1.0j)))

        return context.compile_internal(builder, cpow_internal, sig, args)

    lower(operator.pow, cty, cty)(core)
    lower(operator.ipow, cty, cty)(core)
    lower(pow, cty, cty)(core)

cpow_implement(types.float32, types.complex64)
cpow_implement(types.float64, types.complex128)


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Model\UsersCompany;
use Illuminate\Http\Request;
use Flash;
use Auth;
use App\Model\UsersCompanyRole;

class RolesController extends AdminController
{
    /**
     * Create a new roles controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->page_title = 'Role';
        $this->page_icon = 'fa-address-card';
    }

    /**
     * Swich role of user in specific company
     *
     */
    public function switchRoleUC($u_c_id, $role_id, $type, UsersCompanyRole $usersCompanyRole, UsersCompany $usersCompanies){

        $usersCompany = $usersCompanies->findOrFail($u_c_id);
        $u_c_r = $usersCompanyRole->getUserCompanyRoleId($u_c_id, $role_id);

        //zmena stavu administratora, osetrenie, ze musi ostat vzdy aspon jeden admin
        if ($role_id == 1 && $u_c_r->first() != null){
            $admins = $usersCompanies->getAllAdminsFromCopmany($usersCompany->company_id);
            if (count($admins) == 1){
                flash('Spoločnosť musí mať vždy aspoň jednoho administrátora!', 'danger');
                if($type == 'companies')
                    return redirect(route('admin.companies.detail', $usersCompany->company_id));
                else
                    return redirect(route('admin.users.detail', $usersCompany->user_id));
            }
        }

        if($u_c_r->first() == null){
            $store = $usersCompanyRole->create([
                'user_company_id' => $u_c_id,
                'role_id' => $role_id
            ]);

            Flash::success('Užívatelovi bola pridaná rola!');
        }else{
            $usersCompanyRole = $usersCompanyRole->findOrFail($u_c_r->first()->id);
            $usersCompanyRole->delete();

            Flash::success('Užívatelovi bola odobraná rola!');
        }

        if($type == 'companies')
            return redirect(route('admin.companies.detail', $usersCompany->company_id));
        else
            return redirect(route('admin.users.detail', $usersCompany->user_id));
    }

    //
//    /**
//     * Display a listing of the resource.
//     *
//     * @return \Illuminate\Http\Response
//     */
//    public function index()
//    {
//        return view('admin.roles.index');
//    }
//
//    /**
//     * Show the form for creating a new resource.
//     *
//     * @return \Illuminate\Http\Response
//     */
//    public function create()
//    {
//        //
//    }
//
//    /**
//     * Store a newly created resource in storage.
//     *
//     * @param  \Illuminate\Http\Request  $request
//     * @return \Illuminate\Http\Response
//     */
//    public function store(Request $request)
//    {
//        //
//    }
//
//    /**
//     * Display the specified resource.
//     *
//     * @param  int  $id
//     * @return \Illuminate\Http\Response
//     */
//    public function detail($id)
//    {
//        //
//    }
//
//    /**
//     * Show the form for editing the specified resource.
//     *
//     * @param  int  $id
//     * @return \Illuminate\Http\Response
//     */
//    public function edit($id)
//    {
//        //
//    }
//
//    /**
//     * Update the specified resource in storage.
//     *
//     * @param  \Illuminate\Http\Request  $request
//     * @param  int  $id
//     * @return \Illuminate\Http\Response
//     */
//    public function update(Request $request, $id)
//    {
//        //
//    }
//
//    /**
//     * Remove the specified resource from storage.
//     *
//     * @param  int  $id
//     * @return \Illuminate\Http\Response
//     */
//    public function delete($id)
//    {
//        //
//    }

}


text:
effervescent
============

Tracking a simple Processing sketch over time.


text:
package org.protobeans.mvcsecurity.example.controller;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.protobeans.mvcsecurity.example.Main;
import org.protobeans.testcontainers.mysql.annotation.EnablePerconaContainer;
import org.protobeans.testcontainers.mysql.listener.PerconaContainerListener;
import org.protobeans.testcontainers.selenium.annotation.EnableSeleniumContainer;
import org.protobeans.testcontainers.selenium.annotation.WebDriver;
import org.protobeans.testcontainers.selenium.listener.SeleniumContainerListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes=Main.class)
@EnableSeleniumContainer(dockerHostSshKeyPath = "~/docker_host.ppk")
@EnablePerconaContainer(imageTag = "5.7.16.28", schema = "test_db", rootPassword = "testpass", exposeSchemaAs = "dbSchema", exposeUrlAs = "dbUrl", exposePasswordAs = "dbPassword")
@TestExecutionListeners(value = {SeleniumContainerListener.class, PerconaContainerListener.class}, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
@DirtiesContext
@Ignore
public class SimpleSeleniumTest {
    @Value("${webUrl}")
    private String webUrl;

    @WebDriver
    private RemoteWebDriver webDriver;

    private final static String LOGIN_FORM_TITLE_ID = "loginFormTitle";

    @Test
    public void shouldWork() {
        int a = 5;
        webDriver.get(webUrl + "/signin");

        WebElement loginFormTitle = webDriver.findElement(By.id(LOGIN_FORM_TITLE_ID));
        Assert.assertEquals("LOGIN FORM", loginFormTitle.getText());

        webDriver.findElement(By.id("localeLinkRu")).click();

        WebDriverWait wait = new WebDriverWait(webDriver, 30);
        wait.until(ExpectedConditions.stalenessOf(loginFormTitle));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(LOGIN_FORM_TITLE_ID)));

        loginFormTitle = webDriver.findElement(By.id(LOGIN_FORM_TITLE_ID));
        Assert.assertEquals("ФОРМА АВТОРИЗАЦИИ", loginFormTitle.getText());
    }
}


text:
package pohkahkong.game.rainbow.service;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

/**
 *
 * @author Poh Kah Kong
 *
 */
public class IntentService {
	private static IntentService instance = null;

	private Activity activity;

	private IntentService() {
	}

	public synchronized static IntentService getInstance() {
		if (instance==null) {
			instance = new IntentService();
		}
		return instance;
	}

	public void init(Activity activity) {
		this.activity = activity;
	}

	public void startActivity(Class<?> cls) {
		Intent intent = new Intent(activity, cls);
		activity.startActivity(intent);
    }

	public void startActivityWithExtra(Class<?> cls, Map<String, Integer> extra) {
		Intent intent = new Intent(activity, cls);
		Iterator<Entry<String, Integer>> iterator = extra.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Integer> entry = iterator.next();
			intent.putExtra(entry.getKey(), entry.getValue());
		}
		activity.startActivity(intent);
    }

	public void startUrlActivity(String url) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri data = Uri.parse(url);
		intent.setData(data);
		activity.startActivity(intent);
	}

	public void startService(Class<?> cls) {
		Intent intent = new Intent(activity, cls);
		activity.startService(intent);
	}

	public void stopService(Class<?> cls) {
		Intent intent = new Intent(activity, cls);
		activity.stopService(intent);
	}
}


text:
<?php

/**
 * @file
 * Contains \Triquanta\IziTravel\DataType\FullTour.
 */

namespace Triquanta\IziTravel\DataType;

use Iziteq\IziApiSchemes\Assets;

/**
 * Provides a full tour data type.
 *
 * @todo Add tests for this class.
 */
class FullTour extends FullMtgObjectBase implements FullTourInterface
{

    use TourTrait;
    use PaidDataTrait;

    protected static function getJsonSchemaPath()
    {
        return Assets::getJsonSchemaPath() . '/mtgobjects/tour_full_object';
    }

    public static function createFromData(\stdClass $data)
    {
        /** @var static $tour */
        $tour = parent::createFromData($data);
        $tour->category = $data->category;
        $tour->duration = $data->duration;
        $tour->distance = $data->distance;
        $tour->placement = $data->placement;
        if (isset($data->purchase)) {
           $tour->purchase = Purchase::createFromData($data->purchase);
        }

        return $tour;
    }

}


text:
This is the java client for project ProjectChanged.
The Server part can be found [here](https://github.com/ShengLiu/ProjectChanged).

## Information

### E-mail

If you have any questions, comments, or concerns please e-mail me at:

sheng.kevin.liu@gmail.com

## License

Copyright (c) 2011 - 2012, ProjectChanged
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

+ Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ 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.
+ Neither the name of the ProjectChanged 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.

## Maintain Status

[![Still maintained] (http://stillmaintained.com/ShengLiu/File-Dependency-Client.png)](http://stillmaintained.com/ShengLiu/File-Dependency-Client)

## Maintainers

* [Ke Li](https://github.com/georgeli/)
* [Sheng Liu](https://github.com/ShengLiu/)
* [Xi Cheng](https://github.com/endoplasmicR)
* [Yu Liu](https://github.com/nubster74)


text:
using System;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace System.Xml
{
    public class XmlDictionaryString
    {
        internal const int MinKey = 0;
        internal const int MaxKey = int.MaxValue / 4;

        private readonly IXmlDictionary _dictionary;
        private readonly string _value;
        private readonly int _key;
        private byte[] _buffer;
        private static readonly EmptyStringDictionary s_emptyStringDictionary = new EmptyStringDictionary();

        public XmlDictionaryString(IXmlDictionary dictionary, string value, int key)
        {
            if (dictionary == null)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(dictionary)));
            if (value == null)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
            if (key < MinKey || key > MaxKey)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(key), SR.Format(SR.ValueMustBeInRange, MinKey, MaxKey)));
            _dictionary = dictionary;
            _value = value;
            _key = key;
        }

        internal static string GetString(XmlDictionaryString s)
        {
            if (s == null)
                return null;
            return s.Value;
        }

        public static XmlDictionaryString Empty
        {
            get
            {
                return s_emptyStringDictionary.EmptyString;
            }
        }

        public IXmlDictionary Dictionary
        {
            get
            {
                return _dictionary;
            }
        }

        public int Key
        {
            get
            {
                return _key;
            }
        }

        public string Value
        {
            get
            {
                return _value;
            }
        }

        internal byte[] ToUTF8()
        {
            if (_buffer == null)
                _buffer = System.Text.Encoding.UTF8.GetBytes(_value);
            return _buffer;
        }

        public override string ToString()
        {
            return _value;
        }

        private class EmptyStringDictionary : IXmlDictionary
        {
            private readonly XmlDictionaryString _empty;

            public EmptyStringDictionary()
            {
                _empty = new XmlDictionaryString(this, string.Empty, 0);
            }

            public XmlDictionaryString EmptyString
            {
                get
                {
                    return _empty;
                }
            }

            public bool TryLookup(string value, out XmlDictionaryString result)
            {
                if (value == null)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
                if (value.Length == 0)
                {
                    result = _empty;
                    return true;
                }
                result = null;
                return false;
            }

            public bool TryLookup(int key, out XmlDictionaryString result)
            {
                if (key == 0)
                {
                    result = _empty;
                    return true;
                }
                result = null;
                return false;
            }

            public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
            {
                if (value == null)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
                if (value.Dictionary != this)
                {
                    result = null;
                    return false;
                }
                result = value;
                return true;
            }
        }
    }
}


text:
package mil.emp3.examples.capabilities.common;

public interface UserAction {
    boolean actOn(String userAction);
    String[] getSupportedUserActions(); // Actions shown in specific buttons, maximum of four button can be populated, so
                                        // only the first four items from the array will be processed.
    String[] getMoreActions();          // If test needs more than four action buttons then pass them using this method.
                                        // They will become a menu under the fifth action button

    // A specific test can use the registers menu manager to recreate the test menu. This allows for dynamically changing
    // test menu without existing to drawer test level and allows us to control number of items on the drawer menu.
    void registerTestMenuManager(ITestMenuManager testMenuManager, int maxSupportedActions);
}


text:
layout:     post
title:      "Special interview with Chapavich on Fungjaizine (Thai)"
subtitle:   "บทสัมภาษณ์นิตยสาร Fungjaizine"
date:       2017-05-17 12:00:00
author:     "Phil Chapavich T."
header-img: "public/news/news-default.jpg"
---

# Click the photo to read the article

or this link [https://www.fungjaizine.com/article/interview/phil_wc](https://www.fungjaizine.com/article/interview/phil_wc)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ElementNewLine</title>
<meta name="date" content="2019-11-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.certificate.elements

Class ElementNewLine

java.lang.Object

org.deidentifier.arx.certificate.elements.ElementText

org.deidentifier.arx.certificate.elements.ElementNewLine

All Implemented Interfaces:

Element

public class ElementNewLine
extends ElementText

PDF text element

Author:

Fabian Prasser

Nested Class Summary

Nested classes/interfaces inherited from class org.deidentifier.arx.certificate.elements.ElementText

ElementText.TextStyle

Constructor Summary

Constructors

Constructor and Description

ElementNewLine()

Creates a new instance

Method Summary

Methods inherited from class org.deidentifier.arx.certificate.elements.ElementText

render

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ElementNewLine

public ElementNewLine()

Creates a new instance

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
.default {
    background-color: red;
    padding: 10;
}

.changed {
    background-color: yellow;
    padding: 0 15;
}


text:
<html>
    <head><title>Paypal Receipt</title></head>
    <body>
        Cart ID: {{ cart.cart_uuid }}
        <form action="/hiicart/paypal2/do_pay" method="POST">
            {{ form.as_p }}
            <input type="submit" value="Complete Purchase"/>
        </form>
    </body>
</html>


text:
"""
Test utils
"""
import tempfile

import PIL
import numpy as np

from clouds.util.constants import HealthStatus

def createXors(tgt):
    #create test xor images
    xorIn = [
        ((255, 255, 255, 255), HealthStatus.GOOD),
        ((255, 255, 0, 0), HealthStatus.CLOUDY),
        ((0, 0, 0, 0), HealthStatus.GOOD),
        ((0, 0, 255, 255), HealthStatus.CLOUDY),
    ]
    xorImages = []
    for ar, expected in xorIn:
        npar = np.array(ar, dtype=np.uint8).reshape(2, 2)

        image = PIL.Image.fromarray(npar)

        #pybrain needs a lot of test input. We'll make 20 of each image
        for i in range(20):
            path = tempfile.mktemp(suffix=".png", prefix='xor_', dir=tgt)
            image.save(path)
            xorImages.append((path, expected))
    return xorImages

class MockStream(object):
    def __init__(self, inputQueue):
        """
        A class used as a replacement for stream objects. As data are recieved on the inputQueue,
        make them available to `readline`.
        """
        self.q = inputQueue

    def read(self):
        return [l for l in self.readline()]

    def readline(self):
        """
        Block until an item appears in the queue.
        """
        return self.q.get()

    def close(self):
        pass


text:
package com.vladmihalcea.book.hpjp.hibernate.type;

import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import org.hibernate.Session;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.junit.Test;

import jakarta.persistence.*;
import java.util.Properties;
import java.util.UUID;

import static org.junit.Assert.assertNotNull;

/**
 * @author Vlad Mihalcea
 */
public class PostgresUUIDTest extends AbstractPostgreSQLIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
                Event.class
        };
    }

    @Override
    public void init() {
        executeStatement("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"");
        super.init();
    }

    @Override
    public void destroy() {
        doInJPA(entityManager -> {
            entityManager.createNativeQuery(
                "DROP EXTENSION \"uuid-ossp\" CASCADE"
            ).executeUpdate();
        });
        super.destroy();
    }

    @Test
    public void test() {
        Event _event = doInJPA(entityManager -> {
            Event event = new Event();
            entityManager.persist(event);
            return event;
        });

        assertNotNull(_event.uuid);
    }

    @Entity(name = "Event")
    @Table(name = "event")
    public static class Event {

        @Id
        @GeneratedValue
        private Long id;

        @Generated(GenerationTime.INSERT)
        @Column(columnDefinition = "UUID NOT NULL DEFAULT uuid_generate_v4()", insertable = false)
        private UUID uuid;

    }
}


text:
/**
    A subclass of AudioProcessorParameter that provides an easy way to create a
    parameter which maps onto a given NormalisableRange.

    @see AudioParameterInt, AudioParameterBool, AudioParameterChoice
*/
class JUCE_API  AudioParameterFloat  : public AudioProcessorParameterWithID
{
public:
    /** Creates a AudioParameterFloat with an ID, name, and range.
        On creation, its value is set to the default value.
    */
    AudioParameterFloat (String parameterID, String name,
                         NormalisableRange<float> normalisableRange,
                         float defaultValue);

    /** Creates a AudioParameterFloat with an ID, name, and range.
        On creation, its value is set to the default value.
        For control over skew factors, you can use the other
        constructor and provide a NormalisableRange.
    */
    AudioParameterFloat (String parameterID, String name,
                         float minValue,
                         float maxValue,
                         float defaultValue);

    /** Destructor. */
    ~AudioParameterFloat();

    /** Returns the parameter's current value. */
    float get() const noexcept                  { return value; }
    /** Returns the parameter's current value. */
    operator float() const noexcept             { return value; }

    /** Changes the parameter's current value. */
    AudioParameterFloat& operator= (float newValue);

    /** Provides access to the parameter's range. */
    NormalisableRange<float> range;

private:
    //==============================================================================
    float value, defaultValue;

    float getValue() const override;
    void setValue (float newValue) override;
    float getDefaultValue() const override;
    int getNumSteps() const override;
    String getText (float, int) const override;
    float getValueForText (const String&) const override;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioParameterFloat)
};


text:
package eu.yaga.stockanalyzer.model;

/**
 * Enum containing indices
 */
public enum StockIndex {
    DAX("^GDAXI", "DAX", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=20735&interval=D1&assetName=DAX&exchange=Xetra&dateStart="),
    MDAX("^MDAXI", "MDAX", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=323547&interval=D1&assetName=MDAX&exchange=Xetra&dateStart="),
    SDAX("^SDAXI", "SDAX", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=324724&interval=D1&assetName=SDAX&exchange=Xetra&dateStart="),
    TECDAX("^TECDAX", "TecDAX", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=6623216&interval=D1&assetName=TecDAX&exchange=Xetra&dateStart="),
    SP500("^GSPC", "S&P 500", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=4359526&interval=D1&assetName=S%2526amp%253BP%2520500&exchange=au%C3%9Ferb%C3%B6rslich&dateStart="),
    NASDAQ("^IXIC", "NASDAQ", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=325104&interval=D1&assetName=NASDAQ&exchange=Nasdaq+Global+Indices&dateStart="),
    EUROSTOXX50("^STOXX50E", "EURO STOXX 50", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=193736&interval=D1&assetName=EURO%2520STOXX%252050&exchange=au%C3%9Ferb%C3%B6rslich&dateStart="),
    FTSE100("^FTSE", "FTSE 100", "http://www.onvista.de/onvista/boxes/popup/historicalquote.json?notationId=1918069&interval=D1&assetName=FTSE&exchange=au%C3%9Ferb%C3%B6rslich&dateStart=");

    private final String symbol;
    private final String description;
    private final String onvistaApiUrl;

    StockIndex(String symbol, String description, String onvistaApiUrl) {
        this.symbol = symbol;
        this.description = description;
        this.onvistaApiUrl = onvistaApiUrl;
    }

    public String getSymbol() {
        return symbol;
    }

    public String getDescription() {
        return description;
    }

    public String getOnvistaApiUrl() {
        return onvistaApiUrl;
    }
}