text:
namespace silifuzz {

absl::Status SnapshotGroup::CanAddSnapshot(
    const SnapshotSummary& snapshot_summary) {
  // Cannot add a Snap that is already in group.
  if (id_set_.contains(snapshot_summary.id())) {
    return absl::AlreadyExistsError("Id already exists");
  }

  // Check mappings of snap for conflicts with existing mappings.
  for (const auto& mapping : snapshot_summary.memory_mappings()) {
    // Writable mapping can overlap with mappings having exactly the same
    // permissions if conflict resolution permits.
    if (conflict_resolution_ == kAllowWriteConflictsWithSamePerm &&
        mapping.perms().Has(MemoryPerms::kWritable)) {
      MemoryPerms mapped_perms = mapping.perms().Plus(MemoryPerms::kMapped);
      bool can_add_writable_mapping = true;
      auto check_existing_perms = [&can_add_writable_mapping, mapped_perms](
                                      Snapshot::Address start,
                                      Snapshot::Address limit,
                                      MemoryPerms perms) {
        if (perms != mapped_perms) {
          can_add_writable_mapping = false;
        }
      };
      mapped_memory_map_.Iterate(check_existing_perms, mapping.start_address(),
                                 mapping.limit_address());

      // If the range contains existing mappings, the existing mappings must
      // all have the same permission as the new mapping.
      if (!can_add_writable_mapping) {
        return absl::AlreadyExistsError("writable mapping conflict");
      }
    } else {
      if (mapped_memory_map_.Overlaps(mapping.start_address(),
                                      mapping.limit_address())) {
        return absl::AlreadyExistsError("mapping conflict");
      }
    }
  }
  return absl::OkStatus();
}

void SnapshotGroup::AddSnapshot(const SnapshotSummary& snapshot_summary) {
  DCHECK(CanAddSnapshot(snapshot_summary).ok());

  for (const auto& mapping : snapshot_summary.memory_mappings()) {
    mapped_memory_map_.Add(mapping.start_address(), mapping.limit_address(),
                           mapping.perms().Plus(MemoryPerms::kMapped));
  }
  id_set_.insert(snapshot_summary.id());
}

// ----------------------------------------------------------------------- //

SnapshotPartition::SnapshotPartition(
    size_t num_groups, SnapshotGroup::ConflictResolution conflict_resolution,
    const MappedMemoryMap& conflict_mapped_memory) {
  for (size_t i = 0; i < num_groups; ++i) {
    snapshot_groups_.push_back(
        SnapshotGroup(conflict_resolution, conflict_mapped_memory));
  }
}

SnapshotPartition::SnapshotSummaryList SnapshotPartition::PartitionSnapshots(
    const SnapshotSummaryList& snapshot_summaries) {
  // Compute number of snapshots if all snapshot_summaries can be added
  size_t num_snapshots = snapshot_summaries.size();
  for (const auto& group : snapshot_groups_) {
    num_snapshots += group.size();
  }

  // Try to make groups about the same size.
  const size_t group_size = num_snapshots / snapshot_groups_.size();
  const size_t remainder = num_snapshots % snapshot_groups_.size();
  std::vector<size_t> target_group_size(snapshot_groups_.size());
  for (size_t i = 0; i < snapshot_groups_.size(); ++i) {
    target_group_size[i] = group_size + (i < remainder ? 1 : 0);
  }

  // This loop below can be parallelized by using a thread to handle each group
  // Each group can keep its  own rejected snap list and all individual reject
  // snap lists are merged at the end an iteration into a single list.
  SnapshotPartition::SnapshotSummaryList rejected;
  size_t offset = 0;
  for (size_t i = 0; i < snapshot_groups_.size(); ++i) {
    SnapshotGroup& group = snapshot_groups_[i];
    const ssize_t chunk_size = target_group_size[i] - group.size();
    if (chunk_size == 0) {
      continue;
    }

    DCHECK_GT(chunk_size, 0);
    DCHECK_LE(offset + chunk_size, snapshot_summaries.size());
    for (size_t j = offset; j < offset + chunk_size; ++j) {
      const SnapshotSummary& summary = snapshot_summaries[j];
      if (group.CanAddSnapshot(summary).ok()) {
        group.AddSnapshot(summary);
      } else {
        rejected.push_back(summary);
      }
    }
    offset += chunk_size;
  }
  return rejected;
}

SnapshotGroup::SnapshotSummary::SnapshotSummary(const Snapshot& snapshot)
    : id_(snapshot.id()),
      memory_mappings_(snapshot.memory_mappings()),
      sort_key_(0) {
  int num_end_states = snapshot.expected_end_states().size();
  if (num_end_states == 1) {
    // Bucket by platforms. Empirically, this helps group snapshots that have
    // the same exact expected end state for all platforms into the same
    // shard(s).
    uint64_t bits = 0;
    for (const auto& p : snapshot.expected_end_states()[0].platforms()) {
      bits |= 1 << static_cast<int>(p);
    }
    sort_key_ = -static_cast<int>(bits);
  }
}

}  // namespace silifuzz


text:
gst::Texture::Texture()
    : internal_format(TextureFormat::RGB),
      source_format(PixelFormat::RGB),
      min_filter(FilterMode::LINEAR),
      mag_filter(FilterMode::LINEAR),
      wrap_s(WrapMode::REPEAT),
      wrap_t(WrapMode::REPEAT),
      wrap_r(WrapMode::REPEAT),
      depth_compare(CompareFunc::NONE)
{
}

void gst::Texture::set_internal_format(TextureFormat internal_format)
{
    this->internal_format = internal_format;
    needs_update();
}

void gst::Texture::set_source_format(PixelFormat source_format)
{
    this->source_format = source_format;
    needs_update();
}

void gst::Texture::set_min_filter(FilterMode min_filter)
{
    this->min_filter = min_filter;
    needs_update();
}

void gst::Texture::set_mag_filter(FilterMode mag_filter)
{
    this->mag_filter = mag_filter;
    needs_update();
}

void gst::Texture::set_wrap_s(WrapMode wrap_s)
{
    this->wrap_s = wrap_s;
    needs_update();
}

void gst::Texture::set_wrap_t(WrapMode wrap_t)
{
    this->wrap_t = wrap_t;
    needs_update();
}

void gst::Texture::set_wrap_r(WrapMode wrap_r)
{
    this->wrap_r = wrap_r;
    needs_update();
}

void gst::Texture::set_depth_compare(CompareFunc depth_compare)
{
    this->depth_compare = depth_compare;
    needs_update();
}

gst::TextureFormat gst::Texture::get_internal_format() const
{
    return internal_format;
}

gst::PixelFormat gst::Texture::get_source_format() const
{
    return source_format;
}

gst::FilterMode gst::Texture::get_min_filter() const
{
    return min_filter;
}

gst::FilterMode gst::Texture::get_mag_filter() const
{
    return mag_filter;
}

gst::WrapMode gst::Texture::get_wrap_s() const
{
    return wrap_s;
}

gst::WrapMode gst::Texture::get_wrap_t() const
{
    return wrap_t;
}

gst::WrapMode gst::Texture::get_wrap_r() const
{
    return wrap_r;
}

gst::CompareFunc gst::Texture::get_depth_compare() const
{
    return depth_compare;
}

redpajama_set_name: RedPajamaGithub


text:
from distutils.core import setup

setup(
    name='peabody',
    version='0.2.2',
    author='Jeremy Kitchen',
    author_email='jeremy.kitchen@gorillanation.com',
    packages=['peabody'],
    scripts=['bin/peabody'],
    url='https://github.com/gorillanation/peabody',
    license='LICENSE.txt',
    description='wrapper for cronjobs to provide timeouts, locking, and some other fun features',
    long_description=open('README.rst').read(),
    install_requires=[
        "lockfile",
        "redis",
    ],
)


text:
1410

1411

Black Shard Pass Constructed
When Dorman I finished conquering the human kingdoms in the north, he wanted to move south into the orc kingdoms. In order to provide an additional route of attack for his armies, he set his best engineers and mages to building a traversable pass through the largely impassable mountains. They chose a likely spot, and literally set about destroying a mountain to create a low pass. They succeeded (as did Dorman's advance), but they discovered that the heart of the mountain had been made of almost pure obsidian.


text:
"use strict";

var head;
var uuid = require("@braintree/uuid");
var querystring = require("../../lib/querystring");
var timeouts = {};

function _removeScript(script) {
  if (script && script.parentNode) {
    script.parentNode.removeChild(script);
  }
}

function _createScriptTag(url, callbackName) {
  var script = document.createElement("script");
  var done = false;

  script.src = url;
  script.async = true;
  script.onerror = function () {
    window[callbackName]({ message: "error", status: 500 });
  };

  script.onload = script.onreadystatechange = function () {
    if (done) {
      return;
    }

    if (
      !this.readyState ||
      this.readyState === "loaded" ||
      this.readyState === "complete"
    ) {
      done = true;
      script.onload = script.onreadystatechange = null;
    }
  };

  return script;
}

function _cleanupGlobal(callbackName) {
  try {
    delete window[callbackName];
  } catch (_) {
    window[callbackName] = null;
  }
}

function _setupTimeout(timeout, callbackName) {
  timeouts[callbackName] = setTimeout(function () {
    timeouts[callbackName] = null;

    window[callbackName]({
      error: "timeout",
      status: -1,
    });

    window[callbackName] = function () {
      _cleanupGlobal(callbackName);
    };
  }, timeout);
}

function _setupGlobalCallback(script, callback, callbackName) {
  window[callbackName] = function (response) {
    var status = response.status || 500;
    var err = null;
    var data = null;

    delete response.status;

    if (status >= 400 || status < 200) {
      err = response;
    } else {
      data = response;
    }

    _cleanupGlobal(callbackName);
    _removeScript(script);

    clearTimeout(timeouts[callbackName]);
    callback(err, data, status);
  };
}

function request(options, callback) {
  var script;
  var callbackName = "callback_json_" + uuid().replace(/-/g, "");
  var url = options.url;
  var attrs = options.data;
  var method = options.method;
  var timeout = options.timeout;

  url = querystring.queryify(url, attrs);
  url = querystring.queryify(url, {
    _method: method,
    callback: callbackName,
  });

  script = _createScriptTag(url, callbackName);
  _setupGlobalCallback(script, callback, callbackName);
  _setupTimeout(timeout, callbackName);

  if (!head) {
    head = document.getElementsByTagName("head")[0];
  }

  head.appendChild(script);
}

module.exports = {
  request: request,
};


text:
package org.tallison.lucene.search.concordance.charoffsets;

import java.io.IOException;
import java.util.Set;

public interface DocTokenOffsetsVisitor {

  /**
   *
   * @return doctokenoffsets for reuse
   */
  public DocTokenOffsets getDocTokenOffsets();
  public Set<String> getFields();
  public boolean visit(DocTokenOffsets docTokenOffsets) throws IOException, TargetTokenNotFoundException;
}


text:
require 'digest/sha1'

FactoryGirl.define do
  factory :user, class: Bluereader::User do
    username 'username'
    encrypted_password Digest::SHA1.hexdigest('password')
    full_name 'John Doe'
    logged_in_at Time.now.to_i
    logged_out_at 0
  end

  factory :category, class: Bluereader::Category do
    user
    name 'category'
  end

  factory :feed, class: Bluereader::Feed do
    user
    category
    name 'feed'
    url 'feed.url.com'
  end

  factory :news, class: Bluereader::News do
    user
    feed
    title 'news item'
    description 'description'
    url 'news.url.com'
    read false
    date Time.now.to_i
  end

  factory :setting, class: Bluereader::Setting do
    user
    delete_after_days 0
  end
end


text:
const { broadcast } = require('./broadcast')
const { deepEqual } = require('assert')
const { getCurrentState, setNewState } = require('./state')
const { stateReducer } = require('./state_reducer')
const { coordinators } = require('./coordinators')

describe('broadcast.js', () => {
  describe('broadcast()', () => {
    it('should get current state, call coordinator for new state, and call renderApp with new state', () => {
      let calledWithArgs
      const renderApp = (newState) => {
        calledWithArgs = newState.test
      }
      const type = 'test'
      const payload = Math.random()

      broadcast(getCurrentState, setNewState, stateReducer, coordinators, renderApp, type, payload)

      deepEqual(calledWithArgs, payload)
    })
  })
})


text:
from setuptools import setup

config = {

    'name': 'puzzlepy',
    'version': '0.1.2',
    'author': 'B.A. van den Berg',
    'author_email': 'b.a.vandenberg@gmail.com',
    'url': 'https://github.com/basvandenberg/puzzlepy',
    'description': 'Python package for generating, solving, and testing grid-based puzzle games.',
    'download_url': 'https://github.com/basvandenberg/puzzlepy/releases',
    'license': 'MIT',
    'packages': ['puzzlepy'],
    'classifiers': [
        'Development Status :: 1 - Planning',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3 :: Only',
        'Topic :: Games/Entertainment :: Puzzle Games',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    'scripts': ['bin/sudoku']
}

setup(**config)


text:
import traceback, cPickle
from core.plugins import ProtocolPlugin
from core.decorators import *
from reqs.twisted.internet import reactor
from core.constants import *

class OfflineMessPlugin(ProtocolPlugin):

    commands = {
          "s": "commandSendMessage",
          "sendmessage": "commandSendMessage",
          "inbox": "commandCheckMessages",
          "c": "commandClear",
          "clear": "commandClear",
    }

    def commandSendMessage(self,parts, fromloc, overriderank):
        "/s username message - Guest\nAliases: sendmessage\nSends an message to the users Inbox."
        if len(parts) < 3:
            self.client.sendServerMessage("You must provide a username and a message.")
        else:
            try:
                from_user = self.client.username.lower()
                to_user = parts[1].lower()
                mess = " ".join(parts[2:])
                file = open('config/data/inbox.dat', 'r')
                messages = cPickle.load(file)
                file.close()
                if to_user in messages:
                    messages[to_user]+= "\n" + from_user + ": " + mess
                else:
                    messages[to_user] = from_user + ": " + mess
                file = open('config/data/inbox.dat', 'w')
                cPickle.dump(messages, file)
                file.close()
                self.client.factory.usernames[to_user].MessageAlert()
                self.client.sendServerMessage("A message has been sent to %s." % to_user)
            except:
                self.client.sendServerMessage("Error sending message.")

    def commandCheckMessages(self, parts, fromloc, overriderank):
        "/inbox - Guest\nChecks your Inbox of messages"
        file = open('config/data/inbox.dat', 'r')
        messages = cPickle.load(file)
        file.close()
        if self.client.username.lower() in messages:
            self.client._sendMessage(COLOUR_DARKPURPLE, messages[self.client.username.lower()])
            self.client.sendServerMessage("NOTE: Might want to do /c now.")
        else:
            self.client.sendServerMessage("You do not have any messages.")

    def commandClear(self,parts, fromloc, overriderank):
        "/c - Guest\nAliases: clear\nClears your Inbox of messages"
        target = self.client.username.lower()
        file = open('config/data/inbox.dat', 'r')
        messages = cPickle.load(file)
        file.close()
        if len(parts) == 2:
            target = parts[1]
        elif self.client.username.lower() not in messages:
            self.client.sendServerMessage("You have no messages to clear.")
            return False
        messages.pop(target)
        file = open('config/data/inbox.dat', 'w')
        cPickle.dump(messages, file)
        file.close()
        self.client.sendServerMessage("All your messages have been deleted.")


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>Selectize.js Demo</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
		<link rel="stylesheet" href="css/normalize.css">
		<link rel="stylesheet" href="css/stylesheet.css">

Selectize.js

Dynamic Options

The options are created straight from an array.

					Tools:
					<select id="select-tools" placeholder="Pick a tool..."></select>


text:
import os
import sys

# If ../../wsgi-basic/__init__.py exists, add ../../ to Python search path, so
# that it will override what happens to be installed in
# /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(__file__),
                                   os.pardir,
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir,
                               "wsgi-basic",
                               '__init__.py')):
    sys.path.insert(0, possible_topdir)

from wsgi_basic.server import eventlet as eventlet_server

# entry point.
def main():
    eventlet_server.run(possible_topdir)


text:
$releaseNotesUri = 'https://github.com/tomzorz/Groves/wiki/Release-Notes'
$nugetFileName = 'nuget.exe'
$nuspecPath = 'Groves.nuspec'
$assemblyPath = '../Groves/bin/Release/Groves.dll'

Write-Host 'Groves NuGet packaging script'
Write-Host '-----------------------------'
Write-Host ''
Write-Host -NoNewLine 'Looking for nuget: '
if (!(Test-Path $nugetFileName))
{
    Write-Host 'Not found, downloading!'
    (New-Object System.Net.WebClient).DownloadFile('http://nuget.org/nuget.exe', $nugetFileName)
}
else
{
	Write-Host 'Found!'
}
Write-Host 'Packaging...'
if ((Test-Path $assemblyPath))
{
    $fileInfo = Get-Item $assemblyPath
    $coreFileVersion = $fileInfo.VersionInfo.ProductVersion
    Invoke-Expression ".\$($nugetFileName) pack $($nuspecPath) -Prop version=$($coreFileVersion) -Prop releaseNotes=$($releaseNotesUri)"
    Write-Host 'Packaging successful!'
}
else
{
    Write-Host 'Groves.dll not found.'
}
Write-Host ''
Write-Host -NoNewLine 'Press any key to quit...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');


text:
package org.jivesoftware.openfire.pubsub.cluster;

import org.jivesoftware.openfire.pubsub.Node;
import org.jivesoftware.openfire.pubsub.NodeAffiliate;
import org.jivesoftware.openfire.pubsub.NodeSubscription;
import org.jivesoftware.openfire.pubsub.PubSubService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.util.Optional;

/**
 * A cluster task used to create a pubsub node subscription (a relation between an entity an a pubsub node).
 *
 * Note that this task aims to update in-memory state only: it will not apply affiliation changes to persistent data
 * storage (it is assumed that the cluster node where the task originated takes responsibility for that). As a result,
 * this task might not apply changes if the node that is the subject of this task is currently not loaded in-memory of
 * the cluster node on which this task operates.
 */
public class NewSubscriptionTask extends SubscriptionTask
{
    private static final Logger log = LoggerFactory.getLogger(NewSubscriptionTask.class);

    /**
     * This no-argument constructor is provided for serialization purposes. It should generally not be used otherwise.
     */
    public NewSubscriptionTask()
    {
    }

    /**
     * Constructs a new task that creates a subscription to a pubsub node.
     *
     * @param subscription The to-be-created subscription
     */
    public NewSubscriptionTask(@Nonnull final NodeSubscription subscription)
    {
        super(subscription);
    }

    @Override
    public void run()
    {
        // Note: this implementation should apply changes in-memory state only. It explicitly needs not update
        // persisted data storage, as this can be expected to be done by the cluster node that issued this task.
        // Applying such changes in this task would, at best, needlessly require resources.
        log.debug("[TASK] New subscription : {}", toString());

        final Optional<PubSubService> optService = getServiceIfLoaded();
        final Optional<Node> optNode = getNodeIfLoaded();
        final Optional<NodeSubscription> optSubscription = getSubscriptionIfLoaded();

        // This will only occur if a PEP service is not loaded on this particular cluster node. We can safely do nothing
        // in this case since any changes that might have been applied here will also have been applied to the database
        // by the cluster node where this task originated, meaning that those changes get loaded from the database when
        // the pubsub node is retrieved from the database in the future (OF-2077)
        if (!optService.isPresent() || !optNode.isPresent() || !optSubscription.isPresent()) {
            return;
        }

        final PubSubService service = optService.get();
        final Node node = optNode.get();
        final NodeSubscription subscription = optSubscription.get();

        if (node.getAffiliate(getOwner()) == null)
        {
            // add the missing 'none' affiliation
            NodeAffiliate affiliate = new NodeAffiliate(node, getOwner());
            affiliate.setAffiliation(NodeAffiliate.Affiliation.none);
            node.addAffiliate(affiliate);
        }
        node.addSubscription(subscription);

        if (node.isPresenceBasedDelivery() && node.getSubscriptions(subscription.getOwner()).size() == 1)
        {
            if (subscription.getPresenceStates().isEmpty())
            {
                // Subscribe to the owner's presence since the node is only
                // sending events to online subscribers and this is the first
                // subscription of the user and the subscription is not
                // filtering notifications based on presence show values.
                service.presenceSubscriptionRequired(node, getOwner());
            }
        }
    }
}


text:
This is a Python script for sending emails, which includes various attachment implementations.

Supported Authentication

This integration does not support NTLM authentication. If you are using Exchange as the SMTP server for sending mail and receive the error message: No suitable authentication method found. make sure that you enable Basic Authentication for SMTP authentication in your Exchange environment.

 This example shows Basic Authentication on Exchange 2010:

Configure Mail Sender on Cortex XSOAR

Navigate to Settings > Integrations > Servers & Services.

Search for Mail Sender (New).

Click Add instance to create and configure a new integration instance.

Name: a textual name for the integration instance

Mail server hostname or IP address

SMTP Port

Credentials

Password

Sender address: if the sender address is different than the log-in credentials and password, the sender address must have permission to send emails.

FQDN: Fully Qualified Domain Name, used in EHLO

Use TLS for connection

Do not validate server certificate (not secure)

Click Test to validate the URLs, token, and connection.

Commands

Send email: send-mail

1. Send email

Sends an email.

Basic Command

send-mail

Input

Argument Name
Description

to
Recipient email address

cc
Additional recipient email address

bcc
Additional recipient email address

subject
Subject of the email

body
Content of the email in plain text

htmlBody
Content of the email in html format

replyTo

If recipient chooses to reply, reply will automatically be sent to this email address

attachIDs
Comma-separated list of IDs of war room entries that contain the files you want to attach to the email

attachNames

A comma-separated list of new names, to rename attachments, in correspondence with the order that they were attached to the email.

Examples:

To rename first and third file: attachNames=new_fileName1,,new_fileName3

To rename second and fifth files: attachNames=,new_fileName2,,,new_fileName5

attachCIDs

A comma-separated list of CIDs to embed attachments inside the email itself

transientFile

Textual name for attached file. Multiple files are supported.

transientFileContent

Content for attached file. Multiple files are supported.

Example:

transientFile.1="t1.txt" transientFileContent.1="test 1" transientFile.2="t3.txt" transientFileContent.2="test 3"

transientFileCID

CID for attached file if you want it inline. Multiple files are supported.

Example:

transientFile.1="t1.txt" transientFileContent.1="test 1" transientFileCID.1="t1.txt@xxx.yyy" transientFile.2="t3.txt" transientFileContent.2="test 3"

templateParams

Replace {varname} variables with values from this parameter.

Expected values are in the form of a JSON document

Example:

{
   "varname":{
      "value":"some value",
      "key":"context key"
   }
}

Each var name can either be provided with a value or a context key to retrieve the value from. Note that only context data is accessible for this argument, while incident fields are not.

additionalHeader

Custom header to add to an email.

Command Example

!send-mail to="name@example.com" cc="test@example.com" bcc="admin@example.com" subject="Topic of the day" replyTo="replymail@example.com" attachIDs="111@02a9cf84-c76f-4b2e-8840-c6b2a85c53cf,129@02a9cf84-c86f-4b2e-8840-c6c2a89c53cf" attachNames="notcookie.png,cookie.jpg" attachCIDs="notcookie,mycookie" transientFile="friendly_note.txt" transientFileContent="this is some text" htmlBody="<html>
 <body>
<p>HELLO</p>
 <img src=\"cid:mycookie\"/>
 </body>
</html>"

About CIDs

CIDs work by attaching the image to the email you are sending, and then using standard HTML image tags that reference that image to embed it in the email when the user opens it.

 Example:

<html>
  <body>
    <img src=\"cid:radomimagecid\"/>
  </body>
</html>

CID Limitations

CID is not supported on all email applications. It is supported mainly on Outlook.

On web applications, such as Gmail, adding CID duplicates the attachment: as an actual attachment and embedded in the text body.


text: <!doctype html><table><caption><select><tr>


text:
package ch.squix.extraleague.model.ranking.tasks;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.util.Map;

import org.joda.time.LocalDate;

import ch.squix.extraleague.model.match.Matches;
import ch.squix.extraleague.model.ranking.PlayerRanking;
import ch.squix.extraleague.model.ranking.Ranking;
import ch.squix.extraleague.model.ranking.badge.BadgeEnum;

public class EmperorTask implements RankingTask {

	@Override
	public void rankMatches(Map<String, PlayerRanking> playerRankingMap, Matches matches) {
		LocalDate today = new LocalDate();
		LocalDate weekStart = today.dayOfWeek().withMinimumValue();

		Ranking weekStartRanking = ofy().load().type(Ranking.class).order("createdDate").filter("createdDate > ", weekStart.toDate()).limit(1).first().now();
		if (weekStartRanking != null) {
			for (PlayerRanking weekStartPlayerRanking : weekStartRanking.getPlayerRankings()) {
				if (weekStartPlayerRanking.getBadges().contains(BadgeEnum.King.name())) {
					PlayerRanking playerRanking = playerRankingMap.get(weekStartPlayerRanking.getPlayer());
					if (playerRanking != null) {
						playerRanking.getBadges().add(BadgeEnum.Emperor.name());
					}
				}

			}
		}
	}

}


text:
<?php

namespace OCA\DAV\SystemTag;

use OCP\IUser;
use OCP\SystemTag\ISystemTag;
use OCP\SystemTag\ISystemTagManager;
use OCP\SystemTag\ISystemTagObjectMapper;
use OCP\SystemTag\TagNotFoundException;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\Exception\PreconditionFailed;
use Sabre\DAV\ICollection;

/**
 * Collection containing tags by object id
 */
class SystemTagsObjectMappingCollection implements ICollection {

	/**
	 * @var string
	 */
	private $objectId;

	/**
	 * @var string
	 */
	private $objectType;

	/**
	 * @var ISystemTagManager
	 */
	private $tagManager;

	/**
	 * @var ISystemTagObjectMapper
	 */
	private $tagMapper;

	/**
	 * User
	 *
	 * @var IUser
	 */
	private $user;

	/**
	 * Constructor
	 *
	 * @param string $objectId object id
	 * @param string $objectType object type
	 * @param IUser $user user
	 * @param ISystemTagManager $tagManager tag manager
	 * @param ISystemTagObjectMapper $tagMapper tag mapper
	 */
	public function __construct(
		$objectId,
		$objectType,
		IUser $user,
		ISystemTagManager $tagManager,
		ISystemTagObjectMapper $tagMapper
	) {
		$this->tagManager = $tagManager;
		$this->tagMapper = $tagMapper;
		$this->objectId = $objectId;
		$this->objectType = $objectType;
		$this->user = $user;
	}

	public function createFile($tagId, $data = null) {
		try {
			$tags = $this->tagManager->getTagsByIds([$tagId]);
			$tag = \current($tags);
			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
			}
			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
				throw new Forbidden('No permission to assign tag ' . $tagId);
			}
			/**
			 * regular user who do not belong to whitelisted groups of static tags
			 * can not assign static tags
			 */
			if ((!$tag->isUserEditable() && $tag->isUserAssignable())
				&& !$this->tagManager->canUserUseStaticTagInGroup($tag, $this->user)) {
				throw new Forbidden('No permission to assign tag ' . $tagId);
			}

			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
		} catch (TagNotFoundException $e) {
			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
		}
	}

	public function createDirectory($name) {
		throw new Forbidden('Permission denied to create collections');
	}

	public function getChild($tagId) {
		try {
			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
				$tag = $this->tagManager->getTagsByIds([$tagId]);
				$tag = \current($tag);
				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
					return $this->makeNode($tag);
				}
			}
			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
		} catch (\InvalidArgumentException $e) {
			throw new BadRequest('Invalid tag id', 0, $e);
		} catch (TagNotFoundException $e) {
			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
		}
	}

	public function getChildren() {
		$tagIds = \current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
		if (empty($tagIds)) {
			return [];
		}
		$tags = $this->tagManager->getTagsByIds($tagIds);

		// filter out non-visible tags
		$tags = \array_filter($tags, function ($tag) {
			return $this->tagManager->canUserSeeTag($tag, $this->user);
		});

		return \array_values(\array_map(function ($tag) {
			return $this->makeNode($tag);
		}, $tags));
	}

	public function childExists($tagId) {
		try {
			$result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));

			if ($result) {
				$tags = $this->tagManager->getTagsByIds([$tagId]);
				$tag = \current($tags);
				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
					return false;
				}
			}

			return $result;
		} catch (\InvalidArgumentException $e) {
			throw new BadRequest('Invalid tag id', 0, $e);
		} catch (TagNotFoundException $e) {
			return false;
		}
	}

	public function delete() {
		throw new Forbidden('Permission denied to delete this collection');
	}

	public function getName() {
		return $this->objectId;
	}

	public function setName($name) {
		throw new Forbidden('Permission denied to rename this collection');
	}

	/**
	 * Returns the last modification time, as a unix timestamp
	 *
	 * @return int
	 */
	public function getLastModified() {
		return null;
	}

	/**
	 * Create a sabre node for the mapping of the
	 * given system tag to the collection's object
	 *
	 * @param ISystemTag $tag
	 *
	 * @return SystemTagNode
	 */
	private function makeNode(ISystemTag $tag) {
		return new SystemTagMappingNode(
			$tag,
			$this->objectId,
			$this->objectType,
			$this->user,
			$this->tagManager,
			$this->tagMapper
		);
	}
}


text:
title: final IT Lesson (sad face)
layout: post
author: george.gibbins
permalink: /final-it-lesson-(sad-face)-/
source-id: 1ImMGJ3tOr1_9-v4SQzWdTDAV1-7iAcvu6WhxDY3oml0
published: true
---
In today's lesson we talked about pornography, and the statistics of people at a young age. I learnt how sexting is a criminal offence and how to deal with it if I ever come across sexting by accident. Better be safe than sorry, right?


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE part SYSTEM "part.dtd">

<part>

    <copyright>
      <year>2006</year>
      <year>2013</year>
      <holder>Ericsson AB, All Rights Reserved</holder>
    </copyright>
    <legalnotice>
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  The Initial Developer of the Original Code is Ericsson AB.
    </legalnotice>

    <title>STDLIB Release Notes History</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>

  <description>

The Standard Erlang Libraries application, STDLIB,
      contains modules for manipulating lists, strings and files etc.

  </description>
  <include file="notes_history"></include>
</part>


text:
import * as Backbone from 'backbone';
import { defaults } from 'backbone-decorators';
import * as _ from 'underscore';

// @defaults({})
class <%= name %>Model extends Backbone.Model {

}

export default <%= name %>Model;


text:
require 'rails_helper'

RSpec.describe GamesController, type: :controller do
  let!(:game) { Game.create!(word: 'hang') }
  let(:valid_params) { {lives: 10} }
  let(:invalid_params) { {lives: -1} }

  describe 'GET #index' do
    it 'gets all the games' do
      get :index

      expect(assigns(:games)).to eq [game]
      expect(response).to have_http_status(:ok)
    end
  end

  describe 'GET #show' do
    it 'gets a game' do
      get :show, {id: game.to_param}

      expect(assigns(:game)).to eq game
      expect(response).to have_http_status(:ok)
    end
  end

  describe 'GET #new' do
    it 'makes a new game' do
      get :new, {}

      expect(assigns(:game)).to be_a_new(Game)
    end
  end

  describe 'POST #create' do
    context 'with valid params' do
      it 'creates a new game' do
        expect {
          post :create, {game: valid_params}
        }.to change { Game.count }.by 1
      end

      it 'assigns @game' do
        post :create, {game: valid_params}
        expect(assigns(:game)).to be_a(Game)
        expect(assigns(:game)).to be_persisted
      end

      it 'redirects to the newly created game' do
        post :create, {game: valid_params}
        expect(response).to redirect_to(Game.last)
      end
    end

    context 'with invalid params' do
      it 'assigns a newly created but unsaved game as @game' do
        post :create, {game: invalid_params}
        expect(assigns(:game)).to be_a_new(Game)
      end

      it 're-renders the new template' do
        post :create, {game: invalid_params}
        expect(response).to render_template('new')
      end
    end
  end

end


text:
<?php

namespace Epic\R2RioBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * R2SearchSegment
 *
 * @ORM\Table(name="r2_search_segment")
 * @ORM\Entity(repositoryClass="Epic\R2RioBundle\Entity\R2SearchSegmentRepository")
 */
class R2SearchSegment
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="kind", type="string", length=255)
     */
    private $kind;

    /**
     * @var string
     *
     * @ORM\Column(name="sub_kind", type="string", length=255, nullable=true)
     */
    private $subKind;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_major", type="boolean")
     */
    private $isMajor = false;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_imperial", type="boolean")
     */
    private $isImperial = false;

    /**
     * @var float
     *
     * @ORM\Column(name="distance", type="float")
     */
    private $distance = 0;

    /**
     * @var float
     *
     * @ORM\Column(name="duration", type="float")
     */
    private $duration = 0;

    /**
     * @var string
     *
     * @ORM\Column(name="sName", type="string", length=255, nullable=true)
     */
    private $sName;

    /**
     * @var string
     *
     * @ORM\Column(name="sPos", type="string", length=255, nullable=true)
     */
    private $sPos;

    /**
     * @var string
     *
     * @ORM\Column(name="tName", type="string", length=255, nullable=true)
     */
    private $tName;

    /**
     * @var string
     *
     * @ORM\Column(name="tPos", type="string", length=255, nullable=true)
     */
    private $tPos;

    /**
     * @var string
     *
     * @ORM\Column(name="sCode", type="string", length=255, nullable=true)
     */
    private $sCode;

    /**
     * @var string
     *
     * @ORM\Column(name="tCode", type="string", length=255, nullable=true)
     */
    private $tCode;

    /**
     * @var string
     *
     * @ORM\Column(name="indicativePrice", type="string", length=255, nullable=true)
     */
    private $indicativePrice;

    /**
     * @ORM\ManyToOne(targetEntity="Epic\R2RioBundle\Entity\R2SearchRoute", inversedBy="searchSegments")
     * @ORM\JoinColumn(name="search_route_id", referencedColumnName="id")
     */
    private $searchRoute;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set kind
     *
     * @param string $kind
     * @return R2SearchSegment
     */
    public function setKind($kind)
    {
        $this->kind = $kind;

        return $this;
    }

    /**
     * Get kind
     *
     * @return string
     */
    public function getKind()
    {
        return $this->kind;
    }

    /**
     * Set subKind
     *
     * @param string $subKind
     * @return R2SearchSegment
     */
    public function setSubKind($subKind)
    {
        $this->subKind = $subKind;

        return $this;
    }

    /**
     * Get subKind
     *
     * @return string
     */
    public function getSubKind()
    {
        return $this->subKind;
    }

    /**
     * Set isMajor
     *
     * @param boolean $isMajor
     * @return R2SearchSegment
     */
    public function setIsMajor($isMajor)
    {
        $this->isMajor = $isMajor;

        return $this;
    }

    /**
     * Get isMajor
     *
     * @return boolean
     */
    public function getIsMajor()
    {
        return $this->isMajor;
    }

    /**
     * Set isImperial
     *
     * @param boolean $isImperial
     * @return R2SearchSegment
     */
    public function setIsImperial($isImperial)
    {
        $this->isImperial = $isImperial;

        return $this;
    }

    /**
     * Get isImperial
     *
     * @return boolean
     */
    public function getIsImperial()
    {
        return $this->isImperial;
    }

    /**
     * Set distance
     *
     * @param float $distance
     * @return R2SearchSegment
     */
    public function setDistance($distance)
    {
        $this->distance = $distance;

        return $this;
    }

    /**
     * Get distance
     *
     * @return float
     */
    public function getDistance()
    {
        return $this->distance;
    }

    /**
     * Set duration
     *
     * @param float $duration
     * @return R2SearchSegment
     */
    public function setDuration($duration)
    {
        $this->duration = $duration;

        return $this;
    }

    /**
     * Get duration
     *
     * @return float
     */
    public function getDuration()
    {
        return $this->duration;
    }

    /**
     * Set sName
     *
     * @param string $sName
     * @return R2SearchSegment
     */
    public function setSName($sName)
    {
        $this->sName = $sName;

        return $this;
    }

    /**
     * Get sName
     *
     * @return string
     */
    public function getSName()
    {
        return $this->sName;
    }

    /**
     * Set sPos
     *
     * @param string $sPos
     * @return R2SearchSegment
     */
    public function setSPos($sPos)
    {
        $this->sPos = $sPos;

        return $this;
    }

    /**
     * Get sPos
     *
     * @return string
     */
    public function getSPos()
    {
        return $this->sPos;
    }

    /**
     * Set tName
     *
     * @param string $tName
     * @return R2SearchSegment
     */
    public function setTName($tName)
    {
        $this->tName = $tName;

        return $this;
    }

    /**
     * Get tName
     *
     * @return string
     */
    public function getTName()
    {
        return $this->tName;
    }

    /**
     * Set tPos
     *
     * @param string $tPos
     * @return R2SearchSegment
     */
    public function setTPos($tPos)
    {
        $this->tPos = $tPos;

        return $this;
    }

    /**
     * Get tPos
     *
     * @return string
     */
    public function getTPos()
    {
        return $this->tPos;
    }

    /**
     * Set sCode
     *
     * @param string $sCode
     * @return R2SearchSegment
     */
    public function setSCode($sCode)
    {
        $this->sCode = $sCode;

        return $this;
    }

    /**
     * Get sCode
     *
     * @return string
     */
    public function getSCode()
    {
        return $this->sCode;
    }

    /**
     * Set tCode
     *
     * @param string $tCode
     * @return R2SearchSegment
     */
    public function setTCode($tCode)
    {
        $this->tCode = $tCode;

        return $this;
    }

    /**
     * Get tCode
     *
     * @return string
     */
    public function getTCode()
    {
        return $this->tCode;
    }

    /**
     * Set searchRoute
     *
     * @param \Epic\R2RioBundle\Entity\R2SearchRoute $searchRoute
     * @return R2SearchSegment
     */
    public function setSearchRoute(\Epic\R2RioBundle\Entity\R2SearchRoute $searchRoute = null)
    {
        $this->searchRoute = $searchRoute;

        return $this;
    }

    /**
     * Get searchRoute
     *
     * @return \Epic\R2RioBundle\Entity\R2SearchRoute
     */
    public function getSearchRoute()
    {
        return $this->searchRoute;
    }

    /**
     * Set indicativePrice
     *
     * @param string $indicativePrice
     *
     * @return R2SearchSegment
     */
    public function setIndicativePrice($indicativePrice)
    {
        $this->indicativePrice = $indicativePrice;

        return $this;
    }

    /**
     * Get indicativePrice
     *
     * @return string
     */
    public function getIndicativePrice()
    {
        return $this->indicativePrice;
    }
}