text:
import base64

from ddosso import discourse
from ddosso.handlers import DdossoHandlerMixin

import firenado.tornadoweb
from firenado import service

import hashlib
import hmac

import tornado.escape
from tornado.web import MissingArgumentError

import urllib.parse

class DiscourseSSOHandler(firenado.tornadoweb.TornadoHandler):

    def get(self):
        payload = self.get_argument("sso", strip=False)
        signature = self.get_argument("sig")
        secret = self.component.conf['discourse']['sso']['secret']

        if None in [payload, signature]:
            raise MissingArgumentError("No SSO payload or signature. Please "
                                       "contact support if this problem "
                                       "persists.")
        try:
            assert discourse.sso_has_nounce(payload)
        except AssertionError:
            return MissingArgumentError("Invalid payload. Please contact "
                                        "support if this problem persists.")

        if not discourse.sso_validate(payload, signature, secret):
            raise MissingArgumentError("Invalid payload. Please contact "
                                       "support if this problem persists.")
        self.session.clear()
        self.session.set("payload", payload)
        self.session.set("signature", signature)
        self.session.set("goto", "discourse")
        #self.print(tornado.escape.url_unescape(sso_data['return_sso_url']))
        self.redirect("login")

class DiscourseLoginHandler(firenado.tornadoweb.TornadoHandler,
                            DdossoHandlerMixin):

    @service.served_by("ddosso.services.LoginService")
    def get(self):
        if self.is_logged():
            user = self.login_service.user_to_discourse_data(
                self.get_logged_user())
            self.deliver_auth_back(user)
        else:
            errors = {}
            if self.session.has('login_errors'):
                errors = self.session.get('login_errors')

            ddosso_logo = self.component.conf['logo']
            #print(self.session.get("payload"))
            #print(self.session.get("signature"))

            self.render("login.html", ddosso_conf=self.component.conf,
                        ddosso_logo=ddosso_logo, errors=errors)

    @service.served_by("ddosso.services.LoginService")
    @service.served_by("ddosso.services.UserService")
    def post(self):
        username = self.get_argument('username')
        password = self.get_argument('password')
        errors = {}

        if username == "":
            errors['username'] = "Please inform the username"
        if password == "":
            errors['password'] = "Please inform the password"

        self.session.delete('login_errors')
        user = None
        if not errors:
            user = self.login_service.is_valid(username, password)
            if not user:
                errors['fail'] = "Invalid login"

        if errors:
            self.session.set('login_errors', errors)
            self.redirect("login")
            return
        else:
            from ddosso.ruby_utils import RailsCookie
            from ddosso.handlers import DIASPORA_SESSION_COOKIE
            conf = self.component.conf['diaspora']
            rails_cookie = RailsCookie(conf['cookie']['secret'])
            user = self.user_service.by_username(username)
            session_data = {
                'session_id': str(rails_cookie.gen_cookie_id()),
                'warden.user.user.key': [
                    [user.id],
                    user.encrypted_password[:29],
                ]
            }
            self.set_cookie(DIASPORA_SESSION_COOKIE, rails_cookie.encrypt(
                tornado.escape.json_encode(session_data)))
            self.deliver_auth_back(self.login_service.user_to_discourse_data(
                user))

    def deliver_auth_back(self, user):
        # Getting real ip from the nginx
        x_real_ip = self.request.headers.get("X-Real-IP")
        remote_ip = x_real_ip or self.request.remote_ip
        #self.user_service.set_user_seem(user, remote_ip)

        sso_data = discourse.get_sso_data(self.session.get("payload"))
        params = {
            'nonce': sso_data['nonce'],
            'email': user['email'],
            'external_id': user['guid'],
            'username': user['username'],
            'name': user['name'],
            'avatar_url': user['avatar']
        }

        secret = self.component.conf['discourse']['sso']['secret']
        return_sso_url = tornado.escape.url_unescape(
            sso_data['return_sso_url'])
        return_payload = base64.encodebytes(
            urllib.parse.urlencode(params).encode())
        h = hmac.new(secret.encode(), return_payload, digestmod=hashlib.sha256)
        query_string = urllib.parse.urlencode(
            {'sso': return_payload, 'sig': h.hexdigest()})
        return_path = '%s?%s' % (return_sso_url, query_string)
        self.redirect(return_path)


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

namespace WpfUtils.ValueConverters
{
    /// <summary>
    /// Provides a converter that returns false if the object is null
    /// </summary>
    [ValueConversion(typeof(object), typeof(bool))]
    public class ObjectNotNull : BaseConverter
    {
        public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value != null;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from "react";
import { shallow } from "enzyme";
import Configuration from "./Configuration";

describe("Configuration", () => {
  it("matches snapshot", () => {
    const aConfiguration = shallow(<Configuration />);
    expect(aConfiguration).toMatchSnapshot();
  });
});


text:
<?php
/**
 * @category    Fishpig
 * @package     Fishpig_Wordpress
 * @license     http://fishpig.co.uk/license.txt
 * @author      Ben Tideswell <help@fishpig.co.uk>
 */

class Fishpig_Wordpress_Helper_Plugin extends Fishpig_Wordpress_Helper_Abstract
{
	/**
	 * Install a plugin
	 *
	 * @param string $target
	 * @param string $source
	 * @param bool $enable
	 * @return bool
	 */
	public function install($target, $source, $enable = false)
	{
		if (!is_file($source)) {
			return false;
		}

		$sourceData = @file_get_contents($source);

		if (!$sourceData) {
			return false;
		}

		@mkdir(dirname($target));

		if ((is_file($target) && is_writable($target)) || (!is_file($target) && is_writable(dirname($target)))) {
			@file_put_contents($target, $sourceData);

			if (is_file($target)) {
				return $enable
					? $this->enable(substr($target, strpos($target, 'wp-content/plugins/')+strlen('wp-content/plugins/')))
					: true;
			}
		}

		return false;
	}

	/**
	 * Enable a plugin
	 *
	 * @param string $plugin
	 * @return bool
	 */
	public function enable($plugin)
	{
		if ($this->isEnabled($plugin)) {
			return true;
		}

		if ($db = Mage::helper('wordpress/app')->getDbConnection()) {
			if ($plugins = $this->getWpOption('active_plugins')) {
				$db->update(
					Mage::getSingleton('core/resource')->getTableName('wordpress/option'),
					array('option_value' => serialize(array_merge(unserialize($plugins), array($plugin)))),
					$db->quoteInto('option_name=?', 'active_plugins')
				);
			}
			else {
				$db->insert(
					Mage::getSingleton('core/resource')->getTableName('wordpress/option'),
					array(
						'option_name' => 'active_plugins',
						'option_value' => serialize(array($plugin))
					)
				);
			}

			return true;
		}

		return false;
	}

	/**
	 * Determine whether a WordPress plugin is enabled in the WP admin
	 *
	 * @param string $name
	 * @param bool $format
	 * @return bool
	 */
	public function isEnabled($name)
	{
		$helper = Mage::helper('wordpress');

		$plugins = array();

		if ($plugins = $helper->getWpOption('active_plugins')) {
			$plugins = unserialize($plugins);
		}

		if ($helper->isWordPressMU() && Mage::helper('wpmultisite')->canRun()) {
			if ($networkPlugins = Mage::helper('wpmultisite')->getWpSiteOption('active_sitewide_plugins')) {
				$plugins += (array)unserialize($networkPlugins);
			}
		}

		if ($plugins) {
			foreach($plugins as $a => $b) {
				if (strpos($a . '-' . $b, $name) !== false) {
					return true;
				}
			}
		}

		return false;
	}
}


text:
package org.apache.cloudstack.api.command.admin.config;

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

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseListCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.response.AccountResponse;
import org.apache.cloudstack.api.response.ClusterResponse;
import org.apache.cloudstack.api.response.ConfigurationResponse;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.config.Configuration;

import com.cloud.utils.Pair;

@APICommand(name = "listConfigurations", description = "Lists all configurations.", responseObject = ConfigurationResponse.class,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListCfgsByCmd extends BaseListCmd {
    public static final Logger s_logger = Logger.getLogger(ListCfgsByCmd.class.getName());

    private static final String s_name = "listconfigurationsresponse";

    // ///////////////////////////////////////////////////
    // ////////////// API parameters /////////////////////
    // ///////////////////////////////////////////////////

    @Parameter(name = ApiConstants.CATEGORY, type = CommandType.STRING, description = "lists configurations by category")
    private String category;

    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "lists configuration by name")
    private String configName;

    @Parameter(name = ApiConstants.ZONE_ID,
               type = CommandType.UUID,
               entityType = ZoneResponse.class,
               description = "the ID of the Zone to update the parameter value for corresponding zone")
    private Long zoneId;

    @Parameter(name = ApiConstants.CLUSTER_ID,
               type = CommandType.UUID,
               entityType = ClusterResponse.class,
               description = "the ID of the Cluster to update the parameter value for corresponding cluster")
    private Long clusterId;

    @Parameter(name = ApiConstants.STORAGE_ID,
               type = CommandType.UUID,
               entityType = StoragePoolResponse.class,
               description = "the ID of the Storage pool to update the parameter value for corresponding storage pool")
    private Long storagePoolId;

    @Parameter(name = ApiConstants.ACCOUNT_ID,
               type = CommandType.UUID,
               entityType = AccountResponse.class,
               description = "the ID of the Account to update the parameter value for corresponding account")
    private Long accountId;

    @Parameter(name = ApiConstants.IMAGE_STORE_UUID,
            type = CommandType.UUID,
            entityType = ImageStoreResponse.class,
            description = "the ID of the Image Store to update the parameter value for corresponding image store")
    private Long imageStoreId;

    // ///////////////////////////////////////////////////
    // ///////////////// Accessors ///////////////////////
    // ///////////////////////////////////////////////////

    public String getCategory() {
        return category;
    }

    public String getConfigName() {
        return configName;
    }

    public Long getZoneId() {
        return zoneId;
    }

    public Long getClusterId() {
        return clusterId;
    }

    public Long getStoragepoolId() {
        return storagePoolId;
    }

    public Long getAccountId() {
        return accountId;
    }

    public Long getImageStoreId() {
        return imageStoreId;
    }

    @Override
    public Long getPageSizeVal() {
        Long defaultPageSize = 500L;
        Integer pageSizeInt = getPageSize();
        if (pageSizeInt != null) {
            if (pageSizeInt.longValue() == s_pageSizeUnlimited) {
                defaultPageSize = null;
            } else {
                defaultPageSize = pageSizeInt.longValue();
            }
        }
        return defaultPageSize;
    }

    // ///////////////////////////////////////////////////
    // ///////////// API Implementation///////////////////
    // ///////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public void execute() {
        Pair<List<? extends Configuration>, Integer> result = _mgr.searchForConfigurations(this);
        ListResponse<ConfigurationResponse> response = new ListResponse<ConfigurationResponse>();
        List<ConfigurationResponse> configResponses = new ArrayList<ConfigurationResponse>();
        for (Configuration cfg : result.first()) {
            ConfigurationResponse cfgResponse = _responseGenerator.createConfigurationResponse(cfg);
            cfgResponse.setObjectName("configuration");
            if (getZoneId() != null) {
                cfgResponse.setScope("zone");
            }
            if (getClusterId() != null) {
                cfgResponse.setScope("cluster");
            }
            if (getStoragepoolId() != null) {
                cfgResponse.setScope("storagepool");
            }
            if (getAccountId() != null) {
                cfgResponse.setScope("account");
            }
            if (getImageStoreId() != null){
                cfgResponse.setScope("imagestore");
            }
            configResponses.add(cfgResponse);
        }

        response.setResponses(configResponses, result.second());
        response.setResponseName(getCommandName());
        setResponseObject(response);
    }
}


text:
namespace xrtl {
namespace gfx {
namespace es3 {

// TODO(benvanik): remove the need for this when we have multiple impls.
ref_ptr<ES3SwapChain> ES3SwapChain::Create(
    ref_ptr<ES3PlatformContext> shared_platform_context,
    ES3Queue* primary_queue, ES3Queue* present_queue,
    ref_ptr<MemoryHeap> memory_heap, ref_ptr<ui::Control> control,
    PresentMode present_mode, int image_count,
    absl::Span<const PixelFormat> pixel_formats) {
  WTF_SCOPE0("ES3SwapChain#Create");

  // Create the context targeting the native window.
  // This is the only way in (base) WGL to get a hardware framebuffer.
  auto platform_context = ES3PlatformContext::Create(
      reinterpret_cast<void*>(control->platform_display_handle()),
      reinterpret_cast<void*>(control->platform_handle()),
      std::move(shared_platform_context));
  if (!platform_context) {
    LOG(ERROR) << "Unable to initialize the swap chain WGL platform context";
    return nullptr;
  }

  auto swap_chain = make_ref<ES3PlatformSwapChain>(
      primary_queue, present_queue, memory_heap, control, platform_context,
      present_mode, image_count, pixel_formats);
  return swap_chain;
}

ES3PlatformSwapChain::ES3PlatformSwapChain(
    ES3Queue* primary_queue, ES3Queue* present_queue,
    ref_ptr<MemoryHeap> memory_heap, ref_ptr<ui::Control> control,
    ref_ptr<ES3PlatformContext> platform_context, PresentMode present_mode,
    int image_count, absl::Span<const PixelFormat> pixel_formats)
    : ES3SwapChain(present_mode, image_count, pixel_formats),
      primary_queue_(primary_queue),
      present_queue_(present_queue),
      memory_heap_(std::move(memory_heap)),
      control_(std::move(control)),
      platform_context_(std::move(platform_context)) {
}

ES3PlatformSwapChain::~ES3PlatformSwapChain() = default;

void ES3PlatformSwapChain::PrepareAllocation() {
  static_cast<ES3ObjectLifetimeQueue*>(primary_queue_)
      ->EnqueueObjectAllocation(this, platform_context_);
}

void ES3PlatformSwapChain::Release() {
  static_cast<ES3ObjectLifetimeQueue*>(primary_queue_)
      ->EnqueueObjectDeallocation(this, platform_context_);
}

bool ES3PlatformSwapChain::AllocateOnQueue() {
  WTF_SCOPE0("ES3PlatformSwapChain#AllocateOnQueue");
  ES3PlatformContext::CheckHasContextLock();

  // Query the initial surface size.
  size_ = platform_context_->QuerySize();

  image_create_params_.format = available_pixel_formats_[0];
  image_create_params_.size = Size3D(size_);

  // Allocate framebuffers we'll use for copying.
  framebuffers_.resize(image_count());
  glGenFramebuffers(static_cast<GLsizei>(framebuffers_.size()),
                    framebuffers_.data());

  // Allocate initial images.
  image_views_.resize(image_count());
  pending_image_presents_.resize(image_count());
  pending_acquire_fences_.resize(image_count());
  available_images_semaphore_ =
      Semaphore::Create(image_count() * 2, image_count() * 2);
  auto resize_result = ResizeOnQueue(size_);
  switch (resize_result) {
    case ResizeResult::kSuccess:
      break;
    case ResizeResult::kOutOfMemory:
      LOG(ERROR) << "Failed swap chain init: out of memory";
      return false;
    case ResizeResult::kDeviceLost:
      LOG(ERROR) << "Failed swap chain init: device lost";
      return false;
  }

  // Set swap mode.
  switch (present_mode_) {
    case PresentMode::kImmediate:
      platform_context_->SetSwapBehavior(
          ES3PlatformContext::SwapBehavior::kImmediate);
      break;
    case PresentMode::kLowLatency:
      platform_context_->SetSwapBehavior(
          ES3PlatformContext::SwapBehavior::kSynchronizeAndTear);
      break;
    case PresentMode::kFifo:
      platform_context_->SetSwapBehavior(
          ES3PlatformContext::SwapBehavior::kSynchronize);
      break;
  }

  return true;
}

void ES3PlatformSwapChain::DeallocateOnQueue() {
  WTF_SCOPE0("ES3PlatformSwapChain#DeallocateOnQueue");
  ES3PlatformContext::CheckHasContextLock();
  if (!framebuffers_.empty()) {
    glDeleteFramebuffers(static_cast<GLsizei>(framebuffers_.size()),
                         framebuffers_.data());
    framebuffers_.clear();
  }
  image_views_.clear();
}

SwapChain::ResizeResult ES3PlatformSwapChain::Resize(Size2D new_size) {
  WTF_SCOPE0("ES3PlatformSwapChain#Resize");
  ResizeResult result = ResizeResult::kDeviceLost;
  if (!static_cast<ES3ObjectLifetimeQueue*>(present_queue_)
           ->EnqueueObjectCallbackAndWait(this,
                                          [this, new_size, &result]() {
                                            result = ResizeOnQueue(new_size);
                                            return true;
                                          },
                                          platform_context_)) {
    return ResizeResult::kDeviceLost;
  }
  return result;
}

SwapChain::ResizeResult ES3PlatformSwapChain::ResizeOnQueue(Size2D new_size) {
  WTF_SCOPE0("ES3PlatformSwapChain#ResizeOnQueue");
  ES3PlatformContext::CheckHasContextLock();

  // TODO(benvanik): move this to the queue? won't have to worry about events.
  std::lock_guard<std::mutex> lock_guard(mutex_);

  // Recreate the underlying surface.
  auto recreate_surface_result = platform_context_->RecreateSurface(new_size);
  switch (recreate_surface_result) {
    case ES3PlatformContext::RecreateSurfaceResult::kSuccess:
      // OK.
      break;
    case ES3PlatformContext::RecreateSurfaceResult::kInvalidTarget:
      LOG(ERROR) << "Failed to recreate swap chain surface; invalid target";
      return ResizeResult::kDeviceLost;
    case ES3PlatformContext::RecreateSurfaceResult::kOutOfMemory:
      LOG(ERROR) << "Failed to recreate swap chain surface; out of memory";
      return ResizeResult::kOutOfMemory;
    case ES3PlatformContext::RecreateSurfaceResult::kDeviceLost:
      LOG(ERROR) << "Failed to recreate swap chain surface; device lost";
      return ResizeResult::kDeviceLost;
  }

  // Query the new size, as it may be different than requested.
  size_ = platform_context_->QuerySize();
  image_create_params_.size = Size3D(size_);

  auto usage_mask = Image::Usage::kTransferSource | Image::Usage::kSampled |
                    Image::Usage::kColorAttachment |
                    Image::Usage::kInputAttachment;

  // Resize all images by recreating them.
  for (int i = 0; i < image_views_.size(); ++i) {
    image_views_[i].reset();
  }
  for (int i = 0; i < image_views_.size(); ++i) {
    // Allocate image.
    ref_ptr<Image> image;
    auto result =
        memory_heap_->AllocateImage(image_create_params_, usage_mask, &image);
    DCHECK_EQ(result, MemoryHeap::AllocationResult::kSuccess);
    if (!image) {
      return ResizeResult::kOutOfMemory;
    }

    // Get a view for the target format.
    image_views_[i] =
        image->CreateView(Image::Type::k2D, image_create_params_.format);
  }

  return ResizeResult::kSuccess;
}

SwapChain::AcquireResult ES3PlatformSwapChain::AcquireNextImage(
    std::chrono::milliseconds timeout_millis,
    ref_ptr<QueueFence> signal_queue_fence,
    ref_ptr<ImageView>* out_image_view) {
  WTF_SCOPE0("ES3PlatformSwapChain#AcquireNextImage");

  std::chrono::milliseconds start_time_millis =
      SystemClock::default_clock()->now_millis();

  // Reserve an image index.
  // We'll either use one that is clean or one that does not yet have a waiter.
  int image_index = -1;
  while (image_index == -1) {
    std::chrono::milliseconds elapsed_time_millis =
        SystemClock::default_clock()->now_millis() - start_time_millis;
    if (elapsed_time_millis >= timeout_millis) {
      // Timed out trying.
      return AcquireResult::kTimeout;
    }

    // Wait until at least one image is available.
    // We only wait for the time remaining if we've already tried a bit.
    std::chrono::milliseconds try_timeout_millis =
        timeout_millis - elapsed_time_millis;
    if (Thread::Wait(available_images_semaphore_, try_timeout_millis) !=
        Thread::WaitResult::kSuccess) {
      return AcquireResult::kTimeout;
    }

    std::lock_guard<std::mutex> lock_guard(mutex_);
    // If a discard is pending we'll just fail the acquisition.
    if (is_discard_pending_) {
      available_images_semaphore_->Release(1);
      LOG(WARNING) << "Attempted to acquire an image from the swapchain with a "
                      "discard pending";
      return AcquireResult::kDiscardPending;
    }

    // Prepare the next image.
    // TODO(benvanik): implement other modes (like skipping/etc).
    // First scan for clean images.
    for (int i = 0; i < image_views_.size(); ++i) {
      if (pending_image_presents_[i] == false) {
        // Image is clean - no pending present or waiting acquire.
        // Allow the caller to use it immediately.
        image_index = i;
        pending_image_presents_[i] = true;
        signal_queue_fence.As<ES3QueueFence>()->SignalClient();
        break;
      }
    }
    if (image_index == -1) {
      // No clean images available, try to reserve an in-flight one.
      for (int i = 0; i < image_views_.size(); ++i) {
        if (!pending_acquire_fences_[i]) {
          // Image is in-flight but doesn't yet have a waiter. Reserve it.
          image_index = i;
          pending_acquire_fences_[i] = signal_queue_fence.As<ES3QueueFence>();
          break;
        }
      }
    }
  }
  *out_image_view = image_views_[image_index];

  return AcquireResult::kSuccess;
}

SwapChain::PresentResult ES3PlatformSwapChain::PresentImage(
    ref_ptr<QueueFence> wait_queue_fence, ref_ptr<ImageView> image_view,
    std::chrono::milliseconds present_time_utc_millis) {
  WTF_SCOPE0("ES3PlatformSwapChain#PresentImage");

  int image_index = -1;
  {
    std::lock_guard<std::mutex> lock_guard(mutex_);

    // Map image view back to our index.
    for (int i = 0; i < image_views_.size(); ++i) {
      if (image_views_[i] == image_view) {
        image_index = i;
        break;
      }
    }
    DCHECK_NE(image_index, -1);
    if (image_index == -1) {
      LOG(ERROR)
          << "Attempted to present an image not acquired from the swap chain";
      return PresentResult::kDeviceLost;
    }

    if (is_discard_pending_ && pending_image_presents_[image_index]) {
      // A discard is pending so ignore the present request.
      MarkPresentComplete(image_index);
      return PresentResult::kDiscardPending;
    }
  }

  // Query current size from the context.
  Size2D surface_size = control_->size();
  bool resize_required = surface_size != size_;

  // Submit present request to the context queue.
  auto self = ref_ptr<ES3PlatformSwapChain>(this);
  auto self_token = MoveToLambda(self);
  present_queue_->EnqueueContextCallback(
      platform_context_, {wait_queue_fence},
      [self_token, surface_size, image_index, image_view,
       present_time_utc_millis]() {
        self_token.value->PerformPresent(surface_size, image_index, image_view,
                                         present_time_utc_millis);
      },
      {}, nullptr);

  return resize_required ? PresentResult::kResizeRequired
                         : PresentResult::kSuccess;
}

void ES3PlatformSwapChain::PerformPresent(
    Size2D surface_size, int image_index, ref_ptr<ImageView> image_view,
    std::chrono::milliseconds present_time_utc_millis) {
  WTF_SCOPE0("ES3PlatformSwapChain#PerformPresent");

  {
    std::lock_guard<std::mutex> lock_guard(mutex_);
    if (is_discard_pending_) {
      // A discard is pending, so avoid doing the present and just pretend it
      // completed.
      MarkPresentComplete(image_index);
      return;
    }
  }

  // Map image view back to a GL framebuffer.
  GLuint framebuffer_id = framebuffers_[image_index];
  GLuint texture_id = image_view->image().As<ES3Image>()->texture_id();
  DCHECK_NE(framebuffer_id, 0);
  DCHECK_NE(texture_id, 0);

  // TODO(benvanik): multisample resolve, scaling, etc.

  // Bind our source (read) framebuffer, which is the image the content was
  // rendered into.
  // NOTE: because we use the texture in other framebuffers we *must* reattach
  //       here; GL will implicitly drop attachments from all other framebuffers
  //       when a texture is attached to another.
  glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer_id);
  glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                         GL_TEXTURE_2D, texture_id, 0);
  glReadBuffer(GL_COLOR_ATTACHMENT0);

  // Bind the native swap surface framebuffer.
  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  GLenum draw_buffer = GL_BACK;
  glDrawBuffers(1, &draw_buffer);

  glViewport(0, 0, surface_size.width, surface_size.height);

  glBlitFramebuffer(0, 0, size_.width, size_.height, 0, 0, surface_size.width,
                    surface_size.height, GL_COLOR_BUFFER_BIT, GL_LINEAR);

  // Invalidate the read framebuffer, as we no longer need its contents.
  // TODO(benvanik): verify we can eat the contents.
  GLenum read_invalidate_attachments[] = {
      GL_COLOR_ATTACHMENT0,
  };
  glInvalidateFramebuffer(GL_READ_FRAMEBUFFER,
                          ABSL_ARRAYSIZE(read_invalidate_attachments),
                          read_invalidate_attachments);

  // Detach framebuffer texture to ensure it's not in use on the read frame
  // buffer. This may be required by certain impls due to multi-context use.
  glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                         GL_TEXTURE_2D, 0, 0);
  glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

  if (!platform_context_->SwapBuffers(present_time_utc_millis)) {
    LOG(ERROR) << "Platform SwapBuffers failed";
  }

  // Invalidate the default framebuffer now that we've swapped.
  GLenum draw_invalidate_attachments[] = {
      GL_COLOR,
  };
  glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER,
                          ABSL_ARRAYSIZE(draw_invalidate_attachments),
                          draw_invalidate_attachments);

  // Mark the image as available.
  std::lock_guard<std::mutex> lock_guard(mutex_);
  MarkPresentComplete(image_index);
}

void ES3PlatformSwapChain::MarkPresentComplete(int image_index) {
  if (pending_acquire_fences_[image_index]) {
    // A present is still pending until the pending acquire presents.
    pending_acquire_fences_[image_index]->Signal();
    pending_acquire_fences_[image_index].reset();
  } else {
    pending_image_presents_[image_index] = false;
  }
  available_images_semaphore_->Release(1);
}

void ES3PlatformSwapChain::DiscardPendingPresents() {
  WTF_SCOPE0("ES3PlatformSwapChain#DiscardPendingPresents");

  // Set discard flag so future acquire/present requests will abort immediately.
  {
    std::lock_guard<std::mutex> lock_guard(mutex_);
    is_discard_pending_ = true;
  }

  // Wait for all presents to complete or abort.
  for (int i = 0; i < image_count() * 2; ++i) {
    Thread::Wait(available_images_semaphore_);
  }

  // Done with the discard; from this point on others can acquire images.
  {
    std::lock_guard<std::mutex> lock_guard(mutex_);
    is_discard_pending_ = false;
  }

  // Release all images for reuse.
  available_images_semaphore_->Release(4);
}

}  // namespace es3
}  // namespace gfx
}  // namespace xrtl


text:
'use strict';
/**
 * soilSampleImporter/importField
 * @module soilSampleImporter/importField
 */
angular.module('farmbuild.soilSampleImporter')
    .factory('importField',
    function ($log, importFieldTypes, validations) {
        $log.info("importField ");
        var importField = {};

      /**
       * Returns true if the given import field has a soilClassificationName value to it.
       * This soilClassificationName value should be present in soil-classification>>default.conf.src.js file and
       * be associated with the Key in the import-field-definition>>default.conf.src.js file
       * Refer following files for the associated defaults
       *
       *  import-field-definition>>default.conf.src.js
       *
       *   soil-classification>>default.conf.src.js
       * @method hasClassification
       * @param {string} importFieldName String name of the import field
       * @returns {boolean} true a soilClassification String value is present in the import field definition
       */
        importField.hasClassification = function (importFieldName) {
            var fieldType = importFieldTypes.byName(importFieldName);
            if (fieldType && fieldType.soilClassificationName) {
                return true;
            }
            return false;
        };

      /**
       * Returns true if it is possible to average the soil samples across a paddock for the given import field.
       * Refer following files for the associated defaults
       *
       *  import-field-definition>>default.conf.src.js
       *
       *   soil-classification>>default.conf.src.js
       * @method hasAverage
       * @param  {string} importFieldName String name of the import field as defined in the defaults file
       * @returns {boolean}
       */
        importField.hasAverage = function (importFieldName) {
            var fieldType = importFieldTypes.byName(importFieldName);
            if (fieldType && fieldType.hasAverage) {
                return true;
            }
            return false;
        };

      /**
       * Get all the import field names available for all paddock groups
       * @method getPaddockGroupFields
       * @returns  (Array.<string[]>>)  Array String array containg the import field names
       */
        importField.getPaddockGroupFields = function() {
            var result = [];
            var allImportFields = importFieldTypes.toArray();
            for(var i=0; i<allImportFields.length; i++) {
                if (allImportFields[i].hasAverage) {
                    result.push(allImportFields[i]);
                }
            }
            return result;
        }

        return importField;
    });


text:
package org.opensingular.internal.lib.commons.xml;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Indica que uma classe possui um Element embutido internamente. Permite
 * assim obter o elemento original.
 *
 * @author Daniel C. Bordin
 */
interface EWrapper {

    /**
     * Obtem o Element contido internamente pelo envoltorio.
     *
     * @return Geralmente not null, mas depente do wrapper
     */
    public Element getOriginal();

    /**
     * Desenvelopa se necessário. Ou seja, recupera a elemento original ser for um {@link EWrapper} ou então retorna o próprio
     * valor passado.
     */
    public static Element getOriginal(Element element) {
        return element instanceof EWrapper ? ((EWrapper) element).getOriginal() : element;
    }

    /**
     * Desenvelopa se necessário. Ou seja, recupera a elemento original ser for um {@link EWrapper} ou então retorna o próprio
     * valor passado.
     */
    public static Node getOriginal(Node node) {
        return node instanceof EWrapper ? ((EWrapper) node).getOriginal() : node;
    }
}


text:
<TITLE>Review for Broken Arrow (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Broken Arrow (1996)

reviewed by
James Berardinelli

                                  BROKEN ARROW
                       A film review by James Berardinelli
                        Copyright 1996 James Berardinelli

RATING (0 TO 10): 7.5
Alternative Scale: *** out of ****

United States, 1996
U.S. Release Date: 2/9/96 (wide)
Running Length: 1:48
MPAA Classification: R (Violence, profanity)
Theatrical Aspect Ratio: 2.35:1

Cast: John Travolta, Christian Slater, Samantha Mathis, Delroy Lindo,
      Frank Whaley, Bob Gunton, Howie Long, Vondie Curtis-Hall,
      Kurtwood Smith
Director: John Woo
Producers: Bill Badalato, Mark Gordon, and Terence Chang
Screenplay: Graham Yost
Cinematography: Peter Levy
Music: Hans Zimmer
U.S. Distributor: Twentieth-Century Fox

     By another name, BROKEN ARROW is SPEED gone nuclear.  Yet, despite
all the explosions, violence, special effects, and other choreographed
excesses, this film doesn't have quite the same impact.  It's fun, to be
sure, and the wild ride doesn't let up for a moment, but the level of
tension isn't quite as high.  It probably has something to do with the
premise --  after all, the threat of a nuclear holocaust isn't quite as
unique an idea as a bus that will blow up if it decelerates below 50
mph.

     According to the movie, a "broken arrow" is the military term for a
lost nuclear weapon.  Here, there are two, but they aren't really lost.
Rather, they have been stolen by Air Force Major Vic Deakins (John
Travolta at his most nasty).  Vic thinks the military has done him a
grave injustice by repeatedly passing him over for promotion, and he's
out to get revenge.  His demands are simple:  $250 million or one major
American city will be atomized.

     The only two standing between Vic and a luxurious retirement are
his ex-partner, Captain Riley Hale (Christian Slater), and a Utah park
ranger, Terry Carmichael (Samantha Mathis).  They hook up when Terry
finds Riley after Vic ejects him from a stealth bomber.  The rest of the
film is a cat-and-mouse game, with Riley and Terry chasing Vic, or the
other way around, depending on who has the missiles.  There are all the
requisite close calls and narrow escapes, but nothing quite as nerve-
wracking as watching a bus thunder towards a gap in a freeway-under-
construction.

     The writer of BROKEN ARROW, Graham Yost, also wrote SPEED, which
accounts for many of the similarities.  Director John Woo, best known
for Hong Kong action flicks like THE KILLER and HARD BOILED, is in his
second Hollywood outing (his previous American film, HARD TARGET, was a
Van Damme vehicle).  Woo, whose inimitable style has earned him legions
of fans across the world, seems very much at home in this high-tech
arena.  His characteristic trademarks, such as someone leaping through
the air with guns blazing in both hands, are all in evidence.  As
always, Woo choreographs action like a ballet, creating some of the most
artistic violence to be found anywhere.

     After playing the protagonist in three straight films (PULP
FICTION, GET SHORTY, WHITE MAN'S BURDEN), John Travolta finally gets a
chance to try his hand at a despicable-to-the-core villain.  And, boy,
is he *cool*.  Vic Deakins is one of the most delicious bad guys since
Alan Rickman put on a fake German accent for DIE HARD.  Vic, who loves
"having the power of God at [his] fingertips," is smooth, heartless, and
very dangerous.

     Christian Slater, who plays a radically different role here than in
his other current film, BED OF ROSES, is an adequate hero.  His Riley
doesn't have Vic's twisted charisma, but Slater musters enough screen
presence to get us on his side.  And, while it's nice to see him teamed
up again with Samantha Mathis (the two previously joined forces in PUMP
UP THE VOLUME), the two never really click.  Mathis, who seems better
suited to movies like LITTLE WOMEN,  isn't an especially effective
action star.

     The preposterous thrills in BROKEN ARROW take the characters from a
fight aboard a stealth bomber to a car chase across the flats of Utah to
the bowels of a disused copper mine to a speeding train.  The pace is
relentless; Woo never allows the excitement to flag.  In the end, BROKEN
ARROW is an exhilarating, if empty, experience.  It's the kind of thing
where you turn off your brain and dig your fingernails into the armrest.
It won't be quite as satisfying as a SPEED or DIE HARD, but there's
still enough here to leave anyone exhausted.

- James Berardinelli
e-mail: jberardinell@delphi.com, berardin@bc.cybernex.net
web: http://www2.cybernex.net/~berardin

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import * as React from 'react';
import TimePicker, { TimePickerValue } from 'react-time-picker';

function MyApp() {
    const [value, setValue] = React.useState<TimePickerValue>(new Date());

    return (
        <div>
            <TimePicker value={value} onChange={setValue} />
        </div>
    );
}


text:
require "rubygems"
#require "rspec"
require "rspec" if Gem.source_index.find_name('rspec').map {|x| x.version}.first.version.to_i >= 2
require "spec" if Gem.source_index.find_name('rspec').map {|x| x.version}.first.version.to_i < 2
begin
  require "json"
rescue LoadError
  puts "'json' gem doesn't exist.  Assuming Rails 3 is installed.'"
end

require "action_controller"
require "action_pack"
require "action_view"
require "active_support"
require "active_support/core_ext"

require "ostruct"

$: << (File.dirname(__FILE__) + "/../lib")
require "jquids"

#RSpec.configure do |config|
#end


text:
class GURL;

namespace net {

// The StaticCookiePolicy class implements a static cookie policy that supports
// three modes: allow all, deny all, or block third-party cookies.
class NET_EXPORT StaticCookiePolicy {
 public:
  // Do not change the order of these types as they are persisted in
  // preferences.
  enum Type {
    // Do not perform any cookie blocking.
    ALLOW_ALL_COOKIES = 0,
    // Block all cookies (third-party or not) from begin set or read.
    BLOCK_ALL_COOKIES,
    // Prevent only third-party cookies from being set or read.
    BLOCK_ALL_THIRD_PARTY_COOKIES
  };

  StaticCookiePolicy()
      : type_(StaticCookiePolicy::ALLOW_ALL_COOKIES) {
  }

  explicit StaticCookiePolicy(Type type)
      : type_(type) {
  }

  // Sets the current policy to enforce. This should be called when the user's
  // preferences change.
  void set_type(Type type) { type_ = type; }
  Type type() const { return type_; }

  // Consults the user's third-party cookie blocking preferences to determine
  // whether the URL's cookies can be accessed (i.e., can be get or set).
  int CanAccessCookies(const GURL& url, const GURL& site_for_cookies) const;

 private:
  Type type_;

  DISALLOW_COPY_AND_ASSIGN(StaticCookiePolicy);
};

}  // namespace net

#endif  // NET_BASE_STATIC_COOKIE_POLICY_H_


text:
package com.tqmall.search.canal.handle;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.tqmall.search.canal.RowChangedData;
import com.tqmall.search.canal.Schema;
import com.tqmall.search.canal.action.ActionFactory;
import com.tqmall.search.canal.action.Actionable;
import com.tqmall.search.canal.action.CurrentHandleTable;
import com.tqmall.search.commons.condition.ConditionContainer;
import com.tqmall.search.commons.lang.Function;
import com.tqmall.search.commons.utils.CommonsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by xing on 16/2/22.
 * 收集了每个schema.table{@link CanalInstanceHandle}
 *
 * @see #actionFactory
 */
public abstract class ActionableInstanceHandle<T extends Actionable> extends AbstractCanalInstanceHandle {

    private static final Logger log = LoggerFactory.getLogger(ActionableInstanceHandle.class);

    /**
     * 异常处理方法, 优先根据该Function处理
     */
    private Function<HandleExceptionContext, Boolean> handleExceptionFunction;
    /**
     * 是否忽略处理异常, 默认忽略
     * 优先处理{@link #handleExceptionFunction}
     */
    private volatile boolean ignoreHandleException = true;

    private final ActionFactory<T> actionFactory;

    private final SchemaTableNameAdapter schemaTableNameAdapter;

    /**
     * 当前这在处理的schema.table
     * 每个canalHandle都是单个线程负责调用, 所以这儿也就不用考虑多线程, 如果以后添加了多线程处理, 引入{@link ThreadLocal}
     *
     * @see #startHandle(CanalEntry.Header)
     */
    private Schema<T>.Table currentTable;

    private CanalEntry.EventType currentEventType;

    private volatile boolean userLocalTableFilter = true;

    /**
     * @param connectorFactory       {@link CanalConnector}构造器
     * @param destination            canal实例名称
     * @param actionFactory          table对应action实例
     * @param schemaTableNameAdapter 库, 表名称适配器
     */
    public ActionableInstanceHandle(String destination, ConnectorFactory connectorFactory, ActionFactory<T> actionFactory,
                                    SchemaTableNameAdapter schemaTableNameAdapter) {
        super(destination, connectorFactory);
        Objects.requireNonNull(actionFactory);
        Objects.requireNonNull(schemaTableNameAdapter);
        this.actionFactory = actionFactory;
        this.schemaTableNameAdapter = schemaTableNameAdapter;
    }

    protected abstract HandleExceptionContext buildHandleExceptionContext(RuntimeException exception);

    @Override
    protected void doConnect() {
        canalConnector.connect();
        if (userLocalTableFilter) {
            StringBuilder sb = new StringBuilder();
            for (Schema<T> s : actionFactory) {
                for (Schema<T>.Table t : s) {
                    Map<String, List<String>> nameMap = schemaTableNameAdapter.getRealName(s.getSchemaName(), t.getTableName());
                    for (String schemaName : nameMap.keySet()) {
                        for (String tableName : nameMap.get(schemaName)) {
                            sb.append(schemaName).append('.').append(tableName).append(',');
                        }
                    }
                }
            }
            sb.deleteCharAt(sb.length() - 1);
            canalConnector.subscribe(sb.toString());
        } else {
            canalConnector.subscribe();
        }
    }

    /**
     * {@link Schema.Table#columns}有值, 则对于UPDATE操作过滤更改的字段是否包含在{@link Schema.Table#columns}
     * DELETE, INSERT事件执行条件过滤, 对于UPDATE的过滤不在这做, 比较复杂, 由子类自己实现过滤
     *
     * @param rowChange 更改的数据
     * @return 解析结果
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected final List<RowChangedData> changedDataParse(CanalEntry.RowChange rowChange) {
        List<RowChangedData> dataList = RowChangedData.build(rowChange, currentTable.getRowDataColumns());
        if (CommonsUtils.isEmpty(dataList)) return null;
        ConditionContainer columnCondition;
        if (currentEventType != CanalEntry.EventType.UPDATE
                && (columnCondition = currentTable.getColumnCondition()) != null) {
            //对于INSERT类型的记录更新, 如果条件判断没有通过, 可以认为该更新事件没有发生~~~~
            //对于DELETE类型的记录更新, 如果条件判断没有通过, 可以认为该数据删除之前就不关心, 那这次删除我们更不关心了~~~
            Iterator<RowChangedData> it = dataList.iterator();
            while (it.hasNext()) {
                if (!columnCondition.verify(it.next())) {
                    it.remove();
                }
            }
        }
        return dataList;
    }

    @Override
    protected boolean exceptionHandle(RuntimeException exception, boolean inFinishHandle) {
        try (HandleExceptionContext context = buildHandleExceptionContext(exception)) {
            if (handleExceptionFunction != null) {
                Boolean ignore = handleExceptionFunction.apply(context);
                return ignore == null ? false : ignore;
            } else {
                log.error("canal instance: " + instanceName + " handle table data change occurring exception: " + context.getSchema()
                        + '.' + context.getTable() + ", eventType: " + context.getEventType() + ", changedData size: "
                        + context.getChangedData().size() + ", ignoreHandleException: " + ignoreHandleException + ", inFinishHandle: "
                        + inFinishHandle, exception);
                return ignoreHandleException;
            }
        }
    }

    /**
     * 是否忽略处理异常, 默认忽略
     * 优先处理{@link #handleExceptionFunction}
     */
    public void setIgnoreHandleException(boolean ignoreHandleException) {
        this.ignoreHandleException = ignoreHandleException;
    }

    /**
     * 异常处理方法, 优先根据该Function处理
     *
     * @param handleExceptionFunction 该function的返回结果标识是否忽略该异常, 同{@link #ignoreHandleException}
     * @see #ignoreHandleException
     */
    public void setExceptionHandleFunction(Function<HandleExceptionContext, Boolean> handleExceptionFunction) {
        this.handleExceptionFunction = handleExceptionFunction;
    }

    /**
     * {@link #canalConnector}连接时, 需要执行订阅{@link CanalConnector#subscribe()} / {@link CanalConnector#subscribe(String)}
     * 该变量标识是否使用本地, 即在{@link #actionFactory}中注册的schema, table
     * 如果为true, 订阅时生成filter, 提交直接替换canal server服务端配置的filter信息
     * 如果为false, 以canal server服务端配置的filter信息为准
     * 默认为true, 使用本地的filter配置
     */
    public void setUserLocalTableFilter(boolean userLocalTableFilter) {
        this.userLocalTableFilter = userLocalTableFilter;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public boolean startHandle(CanalEntry.Header header) {
        currentEventType = header.getEventType();
        Map.Entry<String, String> virtualName = schemaTableNameAdapter.getVirtualName(header.getSchemaName(), header.getTableName());
        currentTable = actionFactory.getTable(virtualName.getKey(), virtualName.getValue());
        if (currentTable == null) return false;
        //排除事件类型过滤, 对于UPDATE类型, 如果存在条件判断, 在这儿没有办法执行排除
        if ((RowChangedData.getEventTypeFlag(currentEventType) & currentTable.getForbidEventType()) != 0
                && (currentEventType != CanalEntry.EventType.UPDATE || currentTable.getColumnCondition() == null)) {
            return false;
        }
        T action = currentTable.getAction();
        if (action instanceof CurrentHandleTable) {
            ((CurrentHandleTable<T>) action).setCurrentTable(currentTable);
        }
        return true;
    }

    protected final SchemaTableNameAdapter getSchemaTableNameAdapter() {
        return schemaTableNameAdapter;
    }

    protected final ActionFactory<T> getActionFactory() {
        return actionFactory;
    }

    protected Schema<T>.Table getCurrentTable() {
        return currentTable;
    }

    protected CanalEntry.EventType getCurrentEventType() {
        return currentEventType;
    }

}


text:
layout: page
title: Pearl Enterprises Conference
date: 2016-05-24
author: Alan Nelson
tags: weekly links, java
status: published
summary: Sed ac ornare nibh. Quisque purus nibh, semper.
banner: images/banner/wedding.jpg
booking:
  startDate: 11/23/2018
  endDate: 11/25/2018
  ctyhocn: SCKMTHX
  groupCode: PEC
published: true
---
Maecenas ullamcorper, ante vitae aliquet mollis, eros lacus laoreet eros, id dapibus est quam vitae velit. Fusce consequat tortor posuere elit sodales vestibulum. Praesent laoreet arcu sit amet hendrerit feugiat. Etiam faucibus consectetur condimentum. Donec convallis mi eget lobortis ullamcorper. In sollicitudin diam a nisl posuere tincidunt. Donec pharetra tellus ut porta convallis. Duis scelerisque lacinia nisi at venenatis. Nam sagittis eros quis ligula sagittis porttitor. Nam varius, libero sit amet accumsan porta, mauris elit elementum risus, sed vulputate massa ipsum id sapien. Morbi ullamcorper aliquet magna, sit amet ultricies orci blandit et. Nam sagittis, magna ut molestie efficitur, justo libero fermentum urna, ac tincidunt odio nisl id justo. Proin lectus lorem, ultrices ac dui eu, laoreet rhoncus metus. Integer auctor sodales ante, nec feugiat leo euismod gravida.

* Ut ac elit vel ex accumsan sodales et id lacus
* Cras ullamcorper dolor eget ornare pretium
* Proin mattis metus sit amet turpis mattis porttitor
* Aliquam a sapien a tortor posuere convallis a at leo.

Quisque ac erat purus. Vestibulum porttitor erat sed hendrerit pellentesque. Aenean tincidunt semper interdum. Donec vitae erat ac nisi semper porttitor in quis nisl. Nulla et mi dapibus, faucibus felis id, posuere turpis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas nec dui dapibus, interdum ipsum nec, elementum odio. Aliquam sagittis convallis pulvinar. Quisque faucibus justo at ipsum accumsan finibus eget vel eros. Ut finibus, elit vitae bibendum pretium, quam sem fermentum tellus, quis luctus massa ante et enim. Aliquam commodo mollis consequat. Morbi tortor dolor, condimentum et viverra sed, porttitor tempus est. Maecenas feugiat est eu ex malesuada blandit vitae sit amet risus.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>java-playground</artifactId>
		<groupId>br.com.starcode.playground</groupId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>random-code</artifactId>

	<dependencies>
		<dependency>
		    <groupId>com.miglayout</groupId>
		    <artifactId>miglayout-swing</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
		</dependency>
	</dependencies>
</project>


text:
class UserMailer < ActionMailer::Base
  helper "spree/base"
  default_url_options[:host] = Spree::Config[:site_url]

  def password_reset_instructions(user)
    subject       Spree::Config[:site_name] + ' ' + I18n.t("password_reset_instructions")
    from          Spree::Config[:mails_from]
    recipients    user.email
    bcc           Spree::Config[:mail_bcc]
    sent_on       Time.now
    body          :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
  end

  def count_to_admin(count,email,from1,source,city)
    content_type "text/html"
    from           "customerservice@masthideals.com"
    recipients    ["akvsaran@gmail.com","akvmurlai@gmail.com"]
    subject      " #{from1} User Count in Masthideals.com: #{count}"
    sent_on        Time.now.utc
    body           "email" => email,"count"=>count,"from1"=>from1,"source"=>source,"city"=>city
  end

  def enquiries(enquiry)
    content_type "text/html"
    from           "customerservice@masthideals.com"
    recipients    "ramanavel@gmail.com"
    bcc           Spree::Config[:mail_bcc]
    subject      "New Deal enquiry in masthideals.com #{enquiry.company}"
    sent_on        Time.now.utc
    body           "enquiry" => enquiry
  end

  def success_invite(referer,count,user,current_user)
    content_type "text/html"
    from           "lakshmi@masthideals.com"
    recipients    referer
    bcc           Spree::Config[:mail_bcc]
    subject      "Thanks. You are close to winning the #{call_count(current_user)} Inox ticket(s)."
    sent_on        Time.now.utc
    body           "ref_email" => user,"count"=>count,"current_user"=>current_user
  end

  def plaxo_invite(from,recipients,name,body,money)
    content_type "text/html"
    from           from
    recipients    recipients
    bcc           Spree::Config[:mail_bcc]
    subject      "Become a part of MasthiDeals and earn #{money} MasthiDeals Money which you can use to buy any deal."
    sent_on        Time.now.utc
    body           "name" => name,"from"=>from,"body"=>body,"money"=>money,"code"=>get_code(from)
  end

  def share_this(recipient,from,product,name)
    content_type "text/html"
    from           from
    recipients    recipient
    bcc           Spree::Config[:mail_bcc]
    subject        "#{product.name}"
    sent_on        Time.now.utc
    body           'product' => product,'name'=>name
  end

  def already_registered(user,product)
#   content_type "text/html"
    from           "customerservice@masthideals.com"
    recipients    user.email
    bcc           Spree::Config[:mail_bcc]
    subject        "Welcome to MasthiDeals community. You have already registered with us."
    sent_on        Time.now.utc
    content_type    "multipart/alternative"
    part :content_type => "text/html",
        :body => render_message("already_registered", :product => product,:user=>user)
  end

  def success_sms_registration(user,product)
#   content_type "text/html"
    from           "customerservice@masthideals.com"
    recipients    user.email
    bcc           Spree::Config[:mail_bcc]
    subject        "Welcome to MasthiDeals community. Now you have 100 Rs to spend!"
    sent_on        Time.now.utc
    content_type    "multipart/alternative"
    part :content_type => "text/html",
        :body => render_message("success_sms_registration", :product => product,:email=>user.email)
  end

  def registration(user,product)
    content_type "text/html"
    from           "customerservice@masthideals.com"
    recipients    user.email
    bcc           Spree::Config[:mail_bcc]
    subject        "Welcome to MasthiDeals community"
    sent_on        Time.now.utc
    body           'product' => product
  end

  def users_deal_notify(recipients,product)
#   content_type "text/html"
   from           "customerservice@masthideals.com"
   bcc            recipients
   subject        "New product in Masti Deals - #{product.name}"
   sent_on        Time.now.utc
   content_type    "multipart/alternative"
#   body          "product" => product,"url"=>default_url_options[:host]
    part :content_type => "text/plain",
      :body => "New product in Masti Deals - #{product.name}"
    part :content_type => "text/html",
        :body => render_message("users_deal_notify", :product => product)
 end

  def notify_admin(user, product, msg)
    content_type "text/html"
    from           "customersupport@masthideal.com"
    recipients     user.email
    if msg == "deal_exp_notify"
      subject  "MasthiDeals: deal expiry notification"
    elsif msg == "deal_cancel_notify"
      subject  "MasthiDeals: deal cancel notification"
    elsif msg == "deal_on_notify"
      subject  "MasthiDeals: deal on notification"
    elsif msg == "deal_over_notify"
      subject  "MasthiDeals:  deal over notification"
    end
    sent_on        Time.now.utc
     body          "user" => user,"product"=>product,"vedor"=>product.vendor
 end

 def notify_users_deal_cancel(user_emails, product)
   content_type "text/html"
    bcc user_emails
    from       "customerservice@masthideals.com"
    sent_on    Time.now.utc
    subject    "MasthiDeals: deal cancel notification"
    body       "product" => product.name

 end

 def users_notify_deal_on(user_emails, product)
   content_type "text/html"
    bcc        user_emails
    from       "customerservice@masthideals.com"
    sent_on    Time.now.utc
    subject    "MasthiDeals: deal on notification"
    body       "product" => product.name

 end

 def users_notify_deal_over(user_emails, product)
   content_type "text/html"
    bcc        user_emails
    from       "customerservice@masthideals.com"
    sent_on    Time.now.utc
    subject    "MasthiDeal: deal_over_notification"
    body       "product" => product.name

 end

 def notify_credit_owed_to_admin(user, order)
   content_type "text/html"
    from           "customersupport@masthideal.com"
    recipients     user.email
    subject  "MasthiDeal: Credit Owed for a payment"
    sent_on        Time.now.utc
    body           "order"=>order
 end

 private
 def call_count(user)
   if user.is_cmom==true
     "two"
   else
    "one"
   end
 end

 def get_code(email)
   Refferer.find_by_email(email).code
 end

end


text:
FROM openshift/origin-base

# components from EPEL must be installed in a separate yum install step
RUN yum install -y git tar wget socat hostname epel-release && \
    yum clean all

RUN yum install -y hg golang golang-pkg-darwin-amd64 golang-pkg-windows-amd64 && \
    yum clean all

ENV GOPATH /go

# Get the code coverage tool and godep
RUN go get golang.org/x/tools/cmd/cover github.com/tools/godep

# Mark this as a sti-build container
RUN touch /sti-build-image

WORKDIR /go/src/github.com/openshift/source-to-image

# (set an explicit GOARM of 5 for maximum compatibility)
ENV GOARM 5
ENV PATH $PATH:$GOROOT/bin:$GOPATH/bin

ENV STI_VERSION_FILE /go/src/github.com/openshift/source-to-image/sti-version-defs

# Expect a tar with the source of STI (and /sti-version-defs in the root)
CMD tar mxzf - && hack/build-cross.sh


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Russula graveolens var. rubra Britzelm.

### Remarks
null


text:
Eagleslist is a used textbook buying and trading service for FGCU students. It is currently being developed by Mostofa Ansary, Hermilo Calderon, Michael MacCallum, Andrew Owen, and John Zachariah as a project for Software Engineering Fundamentals (CEN 3031). When complete, Eagleslist will be available as a Windows application.

Our progress building Eagleslist is being tracked at [5-bit.github.io](https://5-bit.github.io).

### Build Instructions

1. Clone this repository to your computer.
2. Open project in Visual Studio 2015.
3. Verify that Humanizer and Newtonsoft.Json have been installed via Nuget.
4. Build and configure [eagleslist-server](https://github.com/5-Bit/eagleslist-server)
5. Build and run Eagleslist in Visual Studio.

--------------------------------------------------

### Screenshots

##### Search Listings

![Search Listings](Screenshots/search.png)

##### New Listing

![New Listing](Screenshots/new.png)

##### Autofill Book Info

![Autofill Book Info](Screenshots/create.png)

##### Profile Page

![Profile Page](Screenshots/profile.png)

##### Browse Listings

![Browse Listings](Screenshots/browse.png)


text:
<!DOCTYPE html>

RMS:


text:
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require '../vendor/autoload.php';

$memcached = new Memcached();
$memcached->setOption(Memcached::OPT_COMPRESSION, false);
$memcached->addServer('127.0.0.1', 11211);

$cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
$cacheDriver->setMemcached($memcached);

$db = \ParagonIE\EasyDB\Factory::create(
    'mysql:host=localhost;dbname=dev_memcached',
    'root',
    ''
);

$session = new php_session\session($db, $cacheDriver, 'test', 0, false);

session_set_save_handler($session, true);

if($_GET['tests'] !== 5) {
    //dont create a session for case 5
    $session->start();
}

switch ($_GET['tests']) {
    case 0:
        $session->set('tests', $_GET['random']);
        break;
    case 1:
        $session->regenerate_id();
        break;
    case 2:
        echo $session->get('tests');
        break;
    case 3:
        $session->logout();
        break;
    case 4:
        //force gc, should delete all sessions in db, who don't have remember_me === 1
        $session->gc(0);
        break;
    case 5:
        //dead
        echo $db->cell('SELECT COUNT(*) FROM sessions WHERE remember_me = 0');
        break;
    case 6:
        $session->remember_me(true);
        break;
    case 7:
        echo $db->cell('SELECT remember_me FROM sessions WHERE id = ?', session_id());
        break;
    case 8:
        $session->remember_me(false);
        break;
}


text:
using System;
using hepa.Datas.Models;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using ZTImage;

namespace hepa.Datas.Datas
{
    public partial class commentsDBDatas
    {
        /// <summary>
        /// 增加
        /// </summary>
        public static bool Create(out int id,T_comments comments)
        {
            string sql="Insert into `comments` (`ArticleID`,`ImportCommentID`,`Content`,`PostTime`,`IsParser`,`ParserTime`,`Tag`) values (@ArticleID,@ImportCommentID,@Content,@PostTime,@IsParser,@ParserTime,@Tag)";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,comments.ArticleID),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,comments.ImportCommentID),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,comments.Content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,comments.PostTime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,comments.IsParser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,comments.ParserTime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,comments.Tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(out id,sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 增加
        /// </summary>
        public static bool Create(T_comments comments)
        {
            string sql="Insert into `comments` (`ArticleID`,`ImportCommentID`,`Content`,`PostTime`,`IsParser`,`ParserTime`,`Tag`) values (@ArticleID,@ImportCommentID,@Content,@PostTime,@IsParser,@ParserTime,@Tag)";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,comments.ArticleID),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,comments.ImportCommentID),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,comments.Content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,comments.PostTime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,comments.IsParser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,comments.ParserTime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,comments.Tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 增加
        /// </summary>
        public static bool Create(Int64 articleid,String importcommentid,String content,Int64 posttime,Int32 isparser,Int64 parsertime,String tag)
        {
            string sql="Insert into `comments` (`ArticleID`,`ImportCommentID`,`Content`,`PostTime`,`IsParser`,`ParserTime`,`Tag`) values (@ArticleID,@ImportCommentID,@Content,@PostTime,@IsParser,@ParserTime,@Tag)";
            DbParameter[] parameters = new DbParameter[] {
                    InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,articleid),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,importcommentid),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,posttime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,isparser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,parsertime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 增加
        /// </summary>
        public static bool CreateContainID(T_comments comments)
        {
            string sql="Insert into `comments` (`CommentID`,`ArticleID`,`ImportCommentID`,`Content`,`PostTime`,`IsParser`,`ParserTime`,`Tag`) values (@CommentID,@ArticleID,@ImportCommentID,@Content,@PostTime,@IsParser,@ParserTime,@Tag)";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,comments.CommentID),
				InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,comments.ArticleID),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,comments.ImportCommentID),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,comments.Content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,comments.PostTime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,comments.IsParser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,comments.ParserTime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,comments.Tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 增加
        /// </summary>
        public static bool CreateContainID(Int64 commentid,Int64 articleid,String importcommentid,String content,Int64 posttime,Int32 isparser,Int64 parsertime,String tag)
        {
            string sql="Insert into `comments` (`CommentID`,`ArticleID`,`ImportCommentID`,`Content`,`PostTime`,`IsParser`,`ParserTime`,`Tag`) values (@CommentID,@ArticleID,@ImportCommentID,@Content,@PostTime,@IsParser,@ParserTime,@Tag)";
            DbParameter[] parameters = new DbParameter[] {
                    InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid),
				InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,articleid),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,importcommentid),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,posttime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,isparser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,parsertime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 删除通过CommentID
        /// </summary>
        public static bool RemoveByCommentID(Int64 commentid)
        {
            string sql="delete from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam ("@CommentID",DbType .Int64,20,commentid )
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改
        /// </summary>
        public static bool Update(T_comments comments)
        {
            string sql="Update `comments` set ArticleID=@ArticleID,ImportCommentID=@ImportCommentID,Content=@Content,PostTime=@PostTime,IsParser=@IsParser,ParserTime=@ParserTime,Tag=@Tag where  `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,comments.CommentID),
				InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,comments.ArticleID),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,comments.ImportCommentID),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,comments.Content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,comments.PostTime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,comments.IsParser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,comments.ParserTime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,comments.Tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改
        /// </summary>
        public static bool Update(Int64 commentid,Int64 articleid,String importcommentid,String content,Int64 posttime,Int32 isparser,Int64 parsertime,String tag)
        {
            string sql="Update `comments` set ArticleID=@ArticleID,ImportCommentID=@ImportCommentID,Content=@Content,PostTime=@PostTime,IsParser=@IsParser,ParserTime=@ParserTime,Tag=@Tag where  `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid),
				InoneDB.Instance.MakeInParam("@ArticleID",DbType.Int64,20,articleid),
				InoneDB.Instance.MakeInParam("@ImportCommentID",DbType.String,255,importcommentid),
				InoneDB.Instance.MakeInParam("@Content",DbType.String,21845,content),
				InoneDB.Instance.MakeInParam("@PostTime",DbType.Int64,255,posttime),
				InoneDB.Instance.MakeInParam("@IsParser",DbType.Int32,255,isparser),
				InoneDB.Instance.MakeInParam("@ParserTime",DbType.Int64,255,parsertime),
				InoneDB.Instance.MakeInParam("@Tag",DbType.String,21845,tag)
            };

            if (InoneDB.Instance.ExecuteNonQuery(sql, CommandType.Text, parameters) > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 读取全部列表
        /// </summary>
        public static List<T_comments> ReadList()
        {
			string sql="select * from `comments`";

			return InoneDB.Instance.Query<T_comments>(sql);
        }

        /// <summary>
        /// 分页读取列表
        /// </summary>
        public static List<T_comments> ReadListPaged(out Int32 fieldCount,Int32 pageIndex,Int32 pageSize)
        {
			string sql="select count(1) from `comments`";
			object ret=InoneDB.Instance.ExecuteScalar (sql);
			fieldCount = TypeConverter.ObjectToInt (ret,0);

            if (fieldCount <= 0)
            {
                return new List<T_comments>();
            }

            Int32 pageCount = fieldCount / pageSize;
            if ((fieldCount % pageSize) > 0)
            {
                pageCount++;
            }

            if (pageIndex <1)
            {
                pageIndex = 1;
            }
            if (pageIndex > pageCount)
            {
                pageIndex = pageCount;
            }

            sql = "select * from `comments` limit "+((pageIndex -1)*pageSize).ToString () +","+pageSize.ToString ();
            return InoneDB.Instance.Query<T_comments>(sql);
        }

        /// <summary>
        /// 通过主键读取实体
        /// </summary>
        public static T_comments ReadByCommentID(Int64 commentid)
        {
            string sql= "select * from `comments`  where `CommentID`=@CommentID";
                DbParameter[] parameters = new DbParameter[] {
                InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
                return InoneDB.Instance.QueryOne<T_comments>(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 通过主键读取ArticleID
        /// </summary>
        public static Int64 GetArticleIDByCommentID(Int64 commentid,Int64 defaultVal)
        {
            string sql="select `ArticleID`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToInt64(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取ArticleID
        /// </summary>
        public static Int64 GetArticleIDByCommentID(Int64 commentid)
        {
            return GetArticleIDByCommentID(commentid,default(Int64));
        }
        /// <summary>
        /// 通过主键读取ImportCommentID
        /// </summary>
        public static String GetImportCommentIDByCommentID(Int64 commentid,String defaultVal)
        {
            string sql="select `ImportCommentID`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToString(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取ImportCommentID
        /// </summary>
        public static String GetImportCommentIDByCommentID(Int64 commentid)
        {
            return GetImportCommentIDByCommentID(commentid,default(String));
        }
        /// <summary>
        /// 通过主键读取Content
        /// </summary>
        public static String GetContentByCommentID(Int64 commentid,String defaultVal)
        {
            string sql="select `Content`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToString(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取Content
        /// </summary>
        public static String GetContentByCommentID(Int64 commentid)
        {
            return GetContentByCommentID(commentid,default(String));
        }
        /// <summary>
        /// 通过主键读取PostTime
        /// </summary>
        public static Int64 GetPostTimeByCommentID(Int64 commentid,Int64 defaultVal)
        {
            string sql="select `PostTime`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToInt64(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取PostTime
        /// </summary>
        public static Int64 GetPostTimeByCommentID(Int64 commentid)
        {
            return GetPostTimeByCommentID(commentid,default(Int64));
        }
        /// <summary>
        /// 通过主键读取IsParser
        /// </summary>
        public static Int32 GetIsParserByCommentID(Int64 commentid,Int32 defaultVal)
        {
            string sql="select `IsParser`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToInt32(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取IsParser
        /// </summary>
        public static Int32 GetIsParserByCommentID(Int64 commentid)
        {
            return GetIsParserByCommentID(commentid,default(Int32));
        }
        /// <summary>
        /// 通过主键读取ParserTime
        /// </summary>
        public static Int64 GetParserTimeByCommentID(Int64 commentid,Int64 defaultVal)
        {
            string sql="select `ParserTime`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToInt64(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取ParserTime
        /// </summary>
        public static Int64 GetParserTimeByCommentID(Int64 commentid)
        {
            return GetParserTimeByCommentID(commentid,default(Int64));
        }
        /// <summary>
        /// 通过主键读取Tag
        /// </summary>
        public static String GetTagByCommentID(Int64 commentid,String defaultVal)
        {
            string sql="select `Tag`  from `comments`  where `CommentID`=@CommentID";
            DbParameter[] parameters = new DbParameter[] {
                  InoneDB.Instance.MakeInParam("@CommentID",DbType.Int64,20,commentid)
            };
            object ret=InoneDB.Instance.ExecuteScalar (sql,CommandType .Text ,parameters);

            try
            {
                return Convert.ToString(ret);
            }
            catch
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 通过主键读取Tag
        /// </summary>
        public static String GetTagByCommentID(Int64 commentid)
        {
            return GetTagByCommentID(commentid,default(String));
        }

    }
}


text:
@interface UCMenuViewController : UIViewController

- (id)initWithProgress:(UCProgressBlock)progress completion:(UCWidgetCompletionBlock)completion;

- (void)presentFrom:(UIViewController *)controller;

@end


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = require('../Subscriber');
var Notification_1 = require('../Notification');
function materialize() {
    return this.lift(new MaterializeOperator());
}
exports.materialize = materialize;
var MaterializeOperator = (function () {
    function MaterializeOperator() {
    }
    MaterializeOperator.prototype.call = function (subscriber) {
        return new MaterializeSubscriber(subscriber);
    };
    return MaterializeOperator;
})();
var MaterializeSubscriber = (function (_super) {
    __extends(MaterializeSubscriber, _super);
    function MaterializeSubscriber(destination) {
        _super.call(this, destination);
    }
    MaterializeSubscriber.prototype._next = function (value) {
        this.destination.next(Notification_1.Notification.createNext(value));
    };
    MaterializeSubscriber.prototype._error = function (err) {
        var destination = this.destination;
        destination.next(Notification_1.Notification.createError(err));
        destination.complete();
    };
    MaterializeSubscriber.prototype._complete = function () {
        var destination = this.destination;
        destination.next(Notification_1.Notification.createComplete());
        destination.complete();
    };
    return MaterializeSubscriber;
})(Subscriber_1.Subscriber);
//# sourceMappingURL=materialize.js.map


text:
package eu.programit.domain;

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

public class Marcel extends Person {
    @Override
    public String getFirstName() {
        return "Marcel";
    }

    @Override
    public List<String> getHobbies() {
        List<String> result = new ArrayList<>(2);
        result.add("boventoonzingen");
        result.add("programmeerpuzzels");
        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PmSys.Components;
using System.Collections;

namespace PmSys.web.Module.PmSys.Projects
{
    public partial class ProjectList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ListBind();
            }
        }
        private void ListBind()
        {
            QueryParam qp = new QueryParam();
            qp.OrderType = 0;
            qp.PageIndex = Pager.CurrentPageIndex;
            qp.PageSize = Pager.PageSize;
            int RecordCount = 0;
            ArrayList lst = BusinessFacade.PM_ProjectsList(qp, out RecordCount);
            GridView1.DataSource = lst;
            GridView1.DataBind();
            this.Pager.RecordCount = RecordCount;
        }

        protected void Pager_PageChanged(object sender, EventArgs e)
        {
            ListBind();
        }
    }
}


text:
var tls = require('tls');
var fs = require('fs');
var net = require('net');

exports.createClient = function (options, callback) {
  options.client = true;
  createComponent(options, callback);
};

exports.createServer = function (options, callback) {
  options.server = true;
  createComponent(options, callback);
};

function createComponent(options, callback) {

  var logLevels = ['error', 'warn', 'info', 'log'];
  var log = {};

  function initLogs(options) {

    if (!options.log_level) {
      options.log_level = 'log';
      console.log('did not receive any log level. using default which is: ' + options.log_level);
    }

    var found = false;
    for (var i = 0; i < logLevels.length; i++) {
      var logLevel = logLevels[i];

      if (!found) {
        log[logLevel] = function (message) {
          console[logLevel](message);
        };
      } else {
        log[logLevel] = function (message) { };
      }

      if (logLevel === options.log_level) {
        found = true;
      }
    }
  }

  initLogs(options);

  if (options.client && options.server || !options.client && !options.server) {
    log.error('invalid ssl tunnel instantiation - should be server or client');
    throw new Error('invalid ssl tunnel instantiation - should be server or client');
  }

  var isClient = options.client;
  var serverPackage = isClient ? tls : net;
  var proxyPackage = isClient ? net : tls;

  // options for the proxy listener
  var proxyOptions = {};
  if (!isClient) {
    proxyOptions = {

      // read the server certificate
      key: fs.readFileSync(options.server_private_cert),
      cert: fs.readFileSync(options.server_public_cert),

      // request client certificate
      requestCert: true,

      // reject unauthorized requests
      rejectUnauthorized: true,

      // validate the CA of the client certificate
      ca: [fs.readFileSync(options.client_public_cert)]
    };
  }

  // options for the server connection
  var serverOptions = {};
  if (isClient) {
    serverOptions = {

      // read the client certificate
      key: fs.readFileSync(options.client_private_cert),
      cert: fs.readFileSync(options.client_public_cert),

      // get public server certificate and mark it as approved
      ca: [fs.readFileSync(options.server_public_cert)]
    };
  }

  var server = proxyPackage.createServer(proxyOptions, function (clientStream) {

    // the socket to the service (either ssltunnel server or real backend server)
    var serverStream = null;

    // pause the input stream until the connection is established
    clientStream.pause();

    // connect to the server
    if (isClient) {
      serverStream = serverPackage.connect(options.server_port, options.server_host, serverOptions);
    } else {
      serverStream = serverPackage.connect(options.server_port, options.server_host);
    }

    // on secureConnect (for client role only)
    serverStream.on("secureConnect", function () {

      log.log('Connected to the ssltunnel server');

      // set TCP keep-alive if needed
      if (options.keep_alive >= 0) {
        log.info('Using TCP Keep-Alive with delay: ' + options.keep_alive);
        serverStream.socket.setKeepAlive(true, options.keep_alive);
      }

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serverStream.pipe(clientStream);
      clientStream.pipe(serverStream);
      clientStream.resume();
    });

    // on connect (for server tole only)
    serverStream.on("connect", function () {

      log.log('Connected to the real BE server');
      //serverStream.setKeepAlive(true, 30000);

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serverStream.pipe(clientStream);
      clientStream.pipe(serverStream);
      clientStream.resume();
    });

    // check that we got no errors when talking to the server
    serverStream.on("error", function (exception) {

      log.info('Error communicating with the server. Error: ' + JSON.stringify(exception));
      clientStream.end();

    });

    // check that we got no errors when talking to the client
    clientStream.on("error", function (exception) {

      log.info('Error communicating with the client. Error: ' + JSON.stringify(exception));
      serverStream.end();

    });

    // print diagnostics when connection to server ends
    serverStream.on("end", function () {
      log.log('connection to server was closed');
    });

    // print diagnostics when connection to client ends
    clientStream.on("end", function () {
      log.log('connection to client was closed');
    });
  });

  server.listen(options.proxy_port);

  // calls the callback when the server is in listening state with the actual port
  server.on("listening", function () {

    if (isClient) {
      log.info('Running \'client\' role. Listening on ' + server.address().port +
            ', encrypting and forwarding to ssltunnel\'s server on ' + options.server_host + ':' + options.server_port);
    } else {
      log.info('Running \'server\' role. Listening on ' + server.address().port +
            ', decrypting and forwarding to real server machine on ' + options.server_host + ':' + options.server_port);
    }

    if (callback) {
      callback(null, server.address().port);
    }
  });
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Network;

namespace GreyWorm
{
    public class AvoidCollosion : IMoveDecider
    {
        private readonly IMoveDecider _another;
	    private readonly int _fillGiveUpLimit;
	    private static Level _level;

        public AvoidCollosion(IMoveDecider another, int fillGiveUpLimit)
        {
	        _another = another;
	        _fillGiveUpLimit = fillGiveUpLimit;
        }

	    public Maybe<Direction> Decide(Level level)
        {
            _level = level;

            var direction = _another.Decide(level);

            if (direction.Any())
            {
                return IsTie(MyPointAfterMove(direction.Single())) ? SafeMove() : direction;
            }

            return SafeMove();
        }

        private Maybe<Direction> SafeMove()
        {
            var possibleDirections = Enum.GetValues(typeof(Direction))
                .Cast<Direction>()
                .Where(CanGo)
                .ToList();

            if (possibleDirections.Count < 1) return Maybe.Empty<Direction>();

            if (possibleDirections.Count == 1) return possibleDirections.Single().ToMaybe();

            return ChooseLargerArea(possibleDirections);
        }

        private Maybe<Direction> ChooseLargerArea(IEnumerable<Direction> directions)
        {
            var orderMap = new Dictionary<Direction, int>()
            {
                {Direction.Down, 0},
                {Direction.Right, 1},
                {Direction.Up, 2},
                {Direction.Left, 3}
            };

            return directions.AsParallel().Select(direction =>
                new Fill
                {
                    Direction = direction,
                    Count = FloodFill(MyPointAfterMove(direction))
                })
                .OrderByDescending(fill => fill.Count)
                .ThenBy(fill => orderMap[fill.Direction])
                .First().Direction.ToMaybe();

        }

        private static bool CanGo(Direction direction)
        {
            var newPoint = MyPointAfterMove(direction);
            return PointIsOpen(newPoint);
        }

        private static bool PointIsOpen(Point point)
        {
            return IsOnMap(point) && _level.Map[point] < 2 && !IsTie(point);
        }

        private static bool IsOnMap(Point point)
        {
            return point.X >= 0 && point.X < _level.Map.Width && point.Y >= 0 && point.Y < _level.Map.Height;
        }

        private static bool IsTie(Point point)
        {
            return _level.EnemyShortestPath.Any() && _level.EnemyShortestPath.First() == point;
        }

        private static Point MyPointAfterMove(Direction direction)
        {
            switch (direction)
            {
                case Direction.Up:
                    return new Point(_level.MyHead.X, _level.MyHead.Y + 1);
                case Direction.Down:
                    return new Point(_level.MyHead.X, _level.MyHead.Y - 1);
                case Direction.Left:
                    return new Point(_level.MyHead.X - 1, _level.MyHead.Y);
                case Direction.Right:
                    return new Point(_level.MyHead.X + 1, _level.MyHead.Y);
                default:
                    throw new ArgumentOutOfRangeException("direction");
            }
        }

        private class Fill
        {
            public Direction Direction { get; set; }
            public int Count { get; set; }
        }

		public int FloodFill(Point startPoint)
		{
			var count = 0;

			var map = _level.Map;

			if (map[startPoint] != 0) return count;

			var painted = new PointArray<bool>(map.Width, map.Height);
			var queue = new Queue<Point>();
			queue.Enqueue(startPoint);

			while (queue.Count > 0)
			{
				var point = queue.Dequeue();

				var west = point.X;
				while (west >= 0 && map[west, point.Y] == 0 && !painted[west, point.Y])
				{
					west -= 1;
				}

				var east = point.X;
				while (east < map.Width && map[east, point.Y] == 0 && !painted[east, point.Y])
				{
					east += 1;
				}

				for (var x = west + 1; x < east; x++)
				{
					painted[x, point.Y] = true;
					count++;

					var north = new Point(x, point.Y + 1);
					if (north.Y < map.Height && map[north] == 0 && !painted[north]) queue.Enqueue(north);

					var south = new Point(x, point.Y - 1);
					if (south.Y >= 0 && map[south] == 0 && !painted[south]) queue.Enqueue(south);
				}

				if (count > _fillGiveUpLimit) return _fillGiveUpLimit;
			}

			return count;
		}

	}
}


text:
__author__ = 'edilio'

from django.contrib import admin
from django.utils import timezone

from apps.ideas.models import *

@admin.register(Idea)
class IdeaAdmin(admin.ModelAdmin):
    list_display = ('name', 'category', 'status', 'market_population', 'market_percentage', 'max_number_of_sales',
                    'monthly_sales',
                    'initial_cost', 'monthly_cost', 'sale_price', 'subscription_fee',
                    'expectation', 'years', 'expectation_x_years')

    list_filter = ('category', 'status', 'created_by',)

    search_fields = ('name', 'long_description')

    fieldsets = (
        (None, {
            'fields': (
                ('name', 'long_description',),
            )
        }),
        (None, {
            'fields': (
                ('category', 'status'),
            )
        }),

        ('Market', {
            'fields': (

                ('market_population', 'market_percentage'),

            )
        }),
        ('Cost', {
            'fields': (

                ('initial_cost', 'monthly_cost'),

            )
        }),
        ('Sales', {
            'fields': (

                ('monthly_sales', 'sale_price', 'subscription_fee'),

            )
        }),
        ('Profits', {
            'fields': (

                ('years', ),

            )
        }),
        ('Dates', {
            'fields': (

                ('created_on', 'created_by', 'modified_by', 'modified_on'),

            )
        }),

        )

    list_per_page = 25

    readonly_fields = ('created_by', 'created_on', 'modified_by', 'modified_on')

    def save_model(self, request, obj, form, change):
        if obj.created_by:
            if form.changed_data:
                obj.modified_by = request.user
                obj.modified_on = timezone.now()
        else:
            obj.created_by = request.user
            obj.created_on = timezone.now()
        obj.save()

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', )

def register(model,admin_class):
    admin.site.register(model, admin_class)


text: go test -v -benchmem -benchtime 5s -bench . | tee benchmark.txt


text:
var fs = require('fs');
var path = require('path');
var util = require('util')
var exec = require('child_process').exec;
function run(cmd, callback){
	console.log('executing: ' + cmd);
	var child = exec(cmd, function (error, stdout, stderr) {
	  console.log('stdout: ', stdout);
	  console.log('stderr: ', stderr);
	  if (error !== null) {
	    console.log('exec error: ' + error);
	  }
	  if(callback)callback();
	});
}

var gridxDir = path.join(path.dirname(module.filename), '../');
var testsDir = path.join(gridxDir, 'tests/');

//Generate the profile
var layers = [];

fs.readdir(testsDir, function(error, files){
	files.forEach(function(file){
		if(file.match(/\.js$/)){
			var name = '' + file.replace(/\.js$/, '');
			layers.push(
					"\n\t\t'" + name + "': {boot: false,customBase: true,include: ["
						+ "\n\t\t\t'gridx/tests/" + name + "'"
						+ "\n\t\t\t,'dojo/selector/acme'"
					+ "\n\t\t]}"
			);
		}else if(file.match(/\.html$/)){
			writeDemoHtml(file);
		}
	});
	var profile = fs.readFileSync(path.join(gridxDir, 'util/demos.profile.tpl.js'), 'utf8');
	var to = path.join(gridxDir, 'demos/profile.js');
	profile = profile.replace('${layers}', layers.join(','));
	fs.writeFileSync(to, profile, 'utf8');

	var dojopath = path.join(gridxDir, '../dojo/dojo.js');
	run('node ' + dojopath + ' load=build action=release profile=' + to);
});

function writeDemoHtml(file){
	//summary:
	//  Copy test case files from 'tests/' folder to 'demos/' folder and convert paths and import the built layer.

	var to = path.join(gridxDir, 'demos/' + file);
	console.log('writing demo path: ' + to);
	var content = fs.readFileSync(path.join(gridxDir, 'tests/' + file), 'utf8');
	content = content.replace(/"support\//g, '"../tests/support/');
	content = content.replace('<script>', '<script src="' + file.replace('.html', '.js') + '"></script>\n\t<script>');
	fs.writeFileSync(to, content, 'utf8');
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Veloci\User\Repository;

use Veloci\Core\Repository\InMemoryRepository;
use Veloci\User\User;

/**
 * Description of InMemoryUserRepository
 *
 * @author christian
 */
class InMemoryUserRepository extends InMemoryRepository implements UserRepository
{
    /**
     * @param string $username
     * @return bool
     */
    public function usernameAlreadyExists(string $username):bool
    {
        $user = $this->getUserByUsername($username);

        return $user !== null;
    }

    /**
     * @param string $username
     * @return User | null
     */
    public function getUserByUsername(string $username)
    {
        $users = $this->getAll();

        /** @var User $user */
        foreach ($users as $user) {
            if ($user->getUsername() === $username) {
                return $user;
            }
        }

        return null;
    }

    protected function getModelClass():string
    {
        return User::class;
    }
}


text:
#ifndef MONGO_UTIL_POOL_H
#define MONGO_UTIL_POOL_H

void mongo_init_MongoPool(TSRMLS_D);

PHP_METHOD(MongoPool, setSize);
PHP_METHOD(MongoPool, getSize);
PHP_METHOD(MongoPool, info);

PHP_METHOD(Mongo, setPoolSize);
PHP_METHOD(Mongo, getPoolSize);
PHP_METHOD(Mongo, poolDebug);

#endif


text:
package com.kotcrab.vis.runtime.assets;

/**
 * Descriptors implementing this interface must reference some texture type asset for exmaple TextureRegion form TextureAtlas
 * @author Kotcrab
 * @see AtlasRegionAsset
 * @see TextureRegionAsset
 */
public interface TextureAssetDescriptor extends VisAssetDescriptor {
}