text:
<#
.Synopsis
 Verify that a VM that looses memory shuts down gracefully.

 Description:
   Verify a VM that looses memory due to another VM starting shuts down cleanly.
   2 VMs are required for this test.

   The testParams have the format of:

      vmName=Name of a VM, enable=[yes|no], minMem= (decimal) [MB|GB|%], maxMem=(decimal) [MB|GB|%],
      startupMem=(decimal) [MB|GB|%], memWeight=(0 < decimal < 100)

   Only the vmName param is taken into consideration. This needs to appear at least twice for
   the test to start.

      Tries=(decimal)
       This controls the number of times the script tries to start the second VM. If not set, a default
       value of 3 is set.
       This is necessary because Hyper-V usually removes memory from a VM only when a second one applies pressure.
       However, the second VM can fail to start while memory is removed from the first.
       There is a 30 second timeout between tries, so 3 tries is a conservative value.

   The following is an example of a testParam for configuring Dynamic Memory

       "Tries=3;enable=yes;minMem=512MB;maxMem=80%;startupMem=80%;memWeight=0;
       enable=yes;minMem=512MB;maxMem=25%;startupMem=25%;memWeight=0"

   All scripts must return a boolean to indicate if the script completed successfully or not.

   .Parameter vmName
    Name of the VM to remove NIC from .

    .Parameter hvServer
    Name of the Hyper-V server hosting the VM.

    .Parameter testParams
    Test data for this test case

    .Example
    setupscripts\DM_CleanShutdown.ps1 -vmName nameOfVM -hvServer localhost -testParams 'sshKey=KEY;ipv4=IPAddress;rootDir=path\to\dir;vm2Name=NameOfVM2'
#>

param([string] $vmName, [string] $hvServer, [string] $testParams)
Set-PSDebug -Strict

#######################################################################
#
# Main script body
#
#######################################################################
#
# Check input arguments
#
if ($vmName -eq $null)
{
    "Error: VM name is null"
    return $False
}

if ($hvServer -eq $null)
{
    "Error: hvServer is null"
    return $False
}

if ($testParams -eq $null)
{
    "Error: testParams is null"
    return $False
}

# Write out test Params
$testParams

# sshKey used to authenticate ssh connection and send commands
$sshKey = $null

# IP Address of first VM
$ipv4 = $null

# Name of first VM
$vm1Name = $null

# Name of second VM
$vm2Name = $null

# number of tries
[int]$tries = 0

# default number of tries
Set-Variable defaultTries -option Constant -value 3

# change working directory to root dir
$testParams -match "RootDir=([^;]+)"
if (-not $?)
{
    "Mandatory param RootDir=Path; not found!"
    return $false
}
$rootDir = $Matches[1]

if (Test-Path $rootDir)
{
    Set-Location -Path $rootDir
    if (-not $?)
    {
        "Error: Could not change directory to $rootDir !"
        return $false
    }
    "Changed working directory to $rootDir"
}
else
{
    "Error: RootDir = $rootDir is not a valid path"
    return $false
}

# Source TCUitls.ps1 for getipv4 and other functions
if (Test-Path ".\setupScripts\TCUtils.ps1")
{
    . .\setupScripts\TCUtils.ps1
}
else
{
    "Error: Could not find setupScripts\TCUtils.ps1"
    return $false
}

# iterator for vmName= parameters. Only 2 are taken into consideration
[int]$netAdapterNameIterator = 0

$params = $testParams.Split(";")
foreach ($p in $params)
{
    $fields = $p.Split("=")

    switch ($fields[0].Trim())
    {

      "ipv4"    { $ipv4    = $fields[1].Trim() }
      "sshKey"  { $sshKey  = $fields[1].Trim() }
      "tries"  { $tries  = $fields[1].Trim() }
      "TC_COVERED" { $TC_COVERED = $fields[1].Trim() }
      "VM2NAME"    { $vm2Name = $fields[1].Trim() }
    }
}

$summaryLog = "${vmName}_summary.log"
del $summaryLog -ErrorAction SilentlyContinue
Write-Output "This script covers test case: ${TC_COVERED}" | Tee-Object -Append -file $summaryLog

if ($tries -le 0)
{
    $tries = $defaultTries
}

$vm1Name = $vmName

$vm1 = Get-VM -Name $vm1Name -ComputerName $hvServer -ErrorAction SilentlyContinue
if (-not $vm1)
{
    "Error: VM $vm1Name does not exist" | Tee-Object -Append -file $summaryLog
    return $false
}

$vm2 = Get-VM -Name $vm2Name -ComputerName $hvServer -ErrorAction SilentlyContinue
if (-not $vm2)
{
    "Error: VM $vm2Name does not exist" | Tee-Object -Append -file $summaryLog
    return $false
}

# sleep 1 minute for VM to start reporting demand
$sleepPeriod = 60
while ($sleepPeriod -gt 0)
{
    # get VM1's Memory
    [int64]$vm1BeforeAssigned = ($vm1.MemoryAssigned/1MB)
    [int64]$vm1BeforeDemand = ($vm1.MemoryDemand/1MB)

    if ($vm1BeforeAssigned -gt 0 -and $vm1BeforeDemand -gt 0)
    {
        break
    }

    $sleepPeriod -= 5
    Start-Sleep -s 5
}

if ($vm1BeforeAssigned -le 0)
{
    "Error: $vm1Name Assigned memory is 0" | Tee-Object -Append -file $summaryLog
    return $false
}

if ($vm1BeforeDemand -le 0)
{
    "Error: $vm1Name Memory demand is 0" | Tee-Object -Append -file $summaryLog
    return $false
}

"VM1 $vm1Name before assigned memory : $vm1BeforeAssigned"
"VM1 $vm1Name before memory demand: $vm1BeforeDemand"
#
# LIS Started VM1, so start VM2
#
Start-Sleep -s 20
StartDependencyVM $vm2Name $hvServer $tries
WaitForVMToReportDemand $vm1Name $hvServer $timeout

# get VM1's Memory
[int64]$vm1AfterAssigned = ($vm1.MemoryAssigned/1MB)
[int64]$vm1AfterDemand = ($vm1.MemoryDemand/1MB)

if ($vm1AfterAssigned -le 0)
{
    "Error: $vm1Name Assigned memory is 0 after $vm2Name started" | Tee-Object -Append -file $summaryLog
    Stop-VM -vmName $vm2Name -ComputerName $hvServer -force
    return $false
}

if ($vm1AfterDemand -le 0)
{
    "Error: $vm1Name Memory demand is 0 after $vm2Name started" | Tee-Object -Append -file $summaryLog
    Stop-VM -vmName $vm2Name -ComputerName $hvServer -force
    return $false
}

"VM1 $vm1Name after assigned memory : $vm1AfterAssigned"
"VM1 $vm1Name after memory demand: $vm1AfterDemand"

# Compute deltas
[int64]$vm1AssignedDelta = [int64]$vm1BeforeAssigned - [int64]$vm1AfterAssigned
[int64]$vm1DemandDelta = [int64]$vm1BeforeDemand - [int64]$vm1AfterDemand

"Deltas after vm2 $vm2Name started"
"  VM1 Assigned : ${vm1AssignedDelta}"
"  VM1 Demand   : ${vm1DemandDelta}"

# Assigned memory needs to have lowered after VM2 starts.
if ($vm1AssignedDelta -le 0)
{
    "Error: $vm1Name did not lower its assigned Memory after vm2 started." | Tee-Object -Append -file $summaryLog
    Stop-VM -vmName $vm2Name -ComputerName $hvServer -force
    return $false
}

$timeout = 120 #seconds

Stop-VM -vmName $vm1Name -ComputerName $hvServer -force
if (-not $?)
{
    "Error: $vm1Name did not shutdown via Hyper-V" | Tee-Object -Append -file $summaryLog
    Stop-VM -vmName $vm2Name -ComputerName $hvServer -force
    return $false
}

# vm1 shut down gracefully via Hyper-V, so shutdown vm2
Stop-VM -vmName $vm2Name -ComputerName $hvServer -force

write-output $true
return $true


text:
package com.clemble.test.random.constructor;

import java.lang.reflect.Modifier;
import java.util.List;
import java.util.function.Supplier;

import com.clemble.test.random.ValueGeneratorFactory;

/**
 * Constructor of empty Objects, for {@link ClassValueGenerator}.
 *
 * @author Anton Oparin
 *
 * @param <T>
 *            parameterized {@link Class}.
 */
abstract public class ClassConstructor<T> {

    /**
     * Returns {@link Object} of defined type.
     *
     * @return empty {@link Object} of defined type.
     */
    abstract public T construct();

    abstract public List<Supplier<?>> getValueGenerators();

    abstract public ClassConstructor<T> clone(List<Supplier<?>> generatorsToUse);

    /**
     * Generates {@link ClassConstructor}. It firstly checks Constructor, than FactoryMethod and the last is Builder based construction.
     *
     * @param <T> the type of object to construct
     * @param classToGenerate
     *            {@link Class} to generate.
     * @param valueGeneratorFactory
     *            {@link ValueGeneratorFactory} to use.
     * @return {@link ClassConstructor} if it is possible to generate one, null otherwise.
     */
	@SuppressWarnings({"unchecked"})
    public static <T> ClassConstructor<T> construct(
        final ClassAccessWrapper<?> classToGenerate,
        final ValueGeneratorFactory valueGeneratorFactory) {
        ClassConstructor<T> objectConstructor = null;
        if ((objectConstructor = ClassConstructorFactory.build(classToGenerate, valueGeneratorFactory)) != null && canConstruct(objectConstructor))
            return objectConstructor;
        if ((objectConstructor = ClassConstructorBuilder.build(classToGenerate, valueGeneratorFactory)) != null && canConstruct(objectConstructor))
            return objectConstructor;
        return (ClassConstructor<T>) ((classToGenerate.getModifiers() & Modifier.ABSTRACT) == 0 ? ClassConstructorSimple.build(classToGenerate, valueGeneratorFactory) : null);
    }

    private static boolean canConstruct(ClassConstructor<?> constructor) {
        try {
            constructor.construct();
            // Step 4.2. We were able to generate value, continue
            return true;
        } catch (Throwable throwable) {
        }
        return false;
    }

}

redpajama_set_name: RedPajamaGithub


text:
import re
import urllib.error
import urllib.parse
import urllib.request

from spiderfoot import SpiderFootEvent, SpiderFootPlugin

sites = {
    # Search string to use, domain name the profile will sit on within
    # those search results.
    "Facebook": [
        "\"{name}\"+site:facebook.com",
        [
            r'[ \'"](https?://[a-z\.]*facebook.[a-z\.]+/[^/"\'<> ]+/?)[\'"]',
            r'(https?%3a%2f%2f[a-z\.]*facebook.[a-z\.]+%2f[^\/"\'<> ]+/?)',
        ],
    ],
    "Google+": [
        "\"{name}\"+site:plus.google.com",
        [
            r'[ \'"](https?://plus.google.[a-z\.]+/\d+[^"\'<>\/ ]+)[\'"]',
            r'(https?%3a%2f%2fplus.google.[a-z\.]+%2f\d+[^\/"\'<> ]+)',
        ],
    ],
    "LinkedIn": [
        "\"{name}\"+site:linkedin.com",
        [
            r'["\' ](https?://[a-z\.]*linkedin.[a-z\.]+/[^\?"\'<> ]+)[\'"]',
            r'(https?%3a%2f%2f[a-z\.]*linkedin.[a-z\.]+%2f[^\?"\'<> ]+)',
        ],
    ],
}

class sfp_socialprofiles(SpiderFootPlugin):

    meta = {
        'name': "Social Media Profile Finder",
        'summary': "Tries to discover the social media profiles for human names identified.",
        'flags': ["slow", "apikey"],
        'useCases': ["Footprint", "Passive"],
        'categories': ["Social Media"],
        'dataSource': {
            'website': "https://developers.google.com/custom-search",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://developers.google.com/custom-search/v1",
                "https://developers.google.com/custom-search/docs/overview",
                "https://cse.google.com/cse"
            ],
            'apiKeyInstructions': [
                "If using Google:",
                "Visit https://developers.google.com/custom-search/v1/introduction",
                "Register a free Google account",
                "Click on 'Get A Key'",
                "Connect a Project",
                "The API Key will be listed under 'YOUR API KEY'",
                "If using Bing:",
                "Visit https://azure.microsoft.com/en-in/services/cognitive-services/bing-web-search-api/",
                "Register a free account",
                "Select on Bing Custom Search",
                "The API keys are listed under 'Key1' and 'Key2' (both should work)"
            ],
            'favIcon': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/developers/images/favicon.png",
            'logo': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/developers/images/favicon.png",
            'description': "Google Custom Search enables you to create a search engine for your website, your blog, or a collection of websites. "
            "You can configure your engine to search both web pages and images. "
            "You can fine-tune the ranking, add your own promotions and customize the look and feel of the search results. "
            "You can monetize the search by connecting your engine to your Google AdSense account.",
        }
    }

    # Default options
    opts = {
        "count": 20,
        "method": "bing",
        "tighten": True,
        "bing_api_key": "",
        "google_api_key": "",
        "google_cse_id": "013611106330597893267:tfgl3wxdtbp",
    }

    # Option descriptions
    optdescs = {
        "count": "Number of bing search engine results of identified profiles to iterate through.",
        "method": "Search engine to use: 'google' or 'bing'.",
        "tighten": "Tighten results by expecting to find the keyword of the target domain mentioned in the social media profile page results?",
        "bing_api_key": "Bing API Key for social media profile search.",
        "google_api_key": "Google API Key for social media profile search.",
        "google_cse_id": "Google Custom Search Engine ID.",
    }

    keywords = None
    results = None
    errorState = False

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = self.tempStorage()
        self.keywords = None
        self.errorState = False

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["HUMAN_NAME"]

    # What events this module produces
    # This is to support the end user in selecting modules based on events
    # produced.
    def producedEvents(self):
        return ["SOCIAL_MEDIA", "RAW_RIR_DATA"]

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data
        self.currentEventSrc = event

        if self.errorState:
            return

        self.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts['google_api_key'] == "" and self.opts['bing_api_key'] == "":
            self.error("You enabled sfp_socialprofiles but did not set a Google or Bing API key!")
            self.errorState = True
            return

        if eventData in self.results:
            self.debug(f"Skipping {eventData}, already checked.")
            return

        self.results[eventData] = True

        if self.keywords is None:
            self.keywords = self.sf.domainKeywords(
                self.getTarget().getNames(), self.opts["_internettlds"]
            )
            if len(self.keywords) == 0:
                self.keywords = None

        for site in sites:
            s = str(sites[site][0]).format(name=eventData)
            searchStr = s.replace(" ", "%20")
            res = None

            if self.opts["method"].lower() == "yahoo":
                self.error(
                    "Yahoo is no longer supported. Please try 'bing' or 'google'."
                )
                return

            if self.opts["method"].lower() == "google":
                res = self.sf.googleIterate(
                    searchString=searchStr,
                    opts={
                        "timeout": self.opts["_fetchtimeout"],
                        "useragent": self.opts["_useragent"],
                        "api_key": self.opts["google_api_key"],
                        "cse_id": self.opts["google_cse_id"],
                    },
                )
                self.__dataSource__ = "Google"

            if self.opts["method"].lower() == "bing":
                res = self.sf.bingIterate(
                    searchString=searchStr,
                    opts={
                        "timeout": self.opts["_fetchtimeout"],
                        "useragent": self.opts["_useragent"],
                        "count": self.opts["count"],
                        "api_key": self.opts["bing_api_key"],
                    },
                )
                self.__dataSource__ = "Bing"

            if res is None:
                self.info("No data returned from " + self.opts["method"] + ".")
                continue

            if self.checkForStop():
                return

            # Submit the results for analysis
            evt = SpiderFootEvent(
                "RAW_RIR_DATA", str(res), self.__name__, event
            )
            self.notifyListeners(evt)

            instances = list()
            for searchDom in sites[site][1]:
                # Search both the urls & the search engine web content
                search_string = " ".join(res["urls"] + [str(res)])

                matches = re.findall(
                    searchDom, search_string, re.IGNORECASE | re.MULTILINE
                )

                if not matches:
                    continue

                for match in matches:
                    self.debug("Match found: " + match)
                    if match in instances:
                        continue
                    else:
                        instances.append(match)

                    if self.checkForStop():
                        return

                    # Fetch the profile page if we are checking
                    # for a firm relationship.
                    # Keywords might be empty if the target was an IP, subnet or name.
                    if self.opts["tighten"] and self.keywords:
                        match = urllib.parse.unquote(match)
                        self.debug(
                            "Tightening results to look for " + str(self.keywords)
                        )
                        pres = self.sf.fetchUrl(
                            match,
                            timeout=self.opts["_fetchtimeout"],
                            useragent=self.opts["_useragent"],
                            verify=False
                        )

                        if pres["content"] is None:
                            continue
                        else:
                            found = False
                            for kw in self.keywords:
                                if re.search(
                                    r"[^a-zA-Z\-\_]" + kw + r"[^a-zA-Z\-\_]",
                                    pres["content"],
                                    re.IGNORECASE,
                                ):
                                    found = True
                            if not found:
                                continue

                    self.info("Social Media Profile found at " + site + ": " + match)
                    match = urllib.parse.unquote(match)
                    evt = SpiderFootEvent(
                        "SOCIAL_MEDIA", site + ": <SFURL>" + match + "</SFURL>", self.__name__, event
                    )
                    self.notifyListeners(evt)

# End of sfp_socialprofiles class


text:
$stdout.sync = true

Repository.where('last_build_finished_at is not null').count(group: :github_language)

rates = Repository.where('last_build_finished_at is not null').count(group: [:last_build_state, :github_language])
groups = rates.group_by { |k, v| k[1] }
stats = groups.map do |lang, values|
  values.inject({ "language" => lang || 'unknown' }) do |result, (state, count)|
    result.merge(state[0] => count)
  end
end

keys = %w(language total passed failed errored cancelled)
puts keys.join(',')

rows = stats.map do |stat|
  values = stat.values
  row = [values.shift]
  row << stat.values[1..-1].inject(&:+)
  keys[1..-1].each { |key| row << (stat[key] || 0) }
  row
end

rows = rows.sort_by { |row| row[1] }.reverse
csv = rows.map { |row| row.join(',') }
puts csv.join("\n")


text:
package org.wickedsource.docxstamper;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Common methods to interact with docx documents.
 */
public abstract class AbstractDocx4jTest {

    private Logger logger = LoggerFactory.getLogger(AbstractDocx4jTest.class);

    private File tempFile;

    protected WordprocessingMLPackage loadDocument(String resourceName) throws Docx4JException {
        InputStream in = getClass().getResourceAsStream(resourceName);
        return WordprocessingMLPackage.load(in);
    }

    /**
     * Saves the given document into a temporal ByteArrayOutputStream and loads it from there again. This is useful to
     * check if changes in the Docx4j object structure are really transported into the XML of the .docx file.
     *
     * @param document the document to save and load again.
     * @return the document after it has been saved and loaded again.
     */
    protected WordprocessingMLPackage saveAndLoadDocument(WordprocessingMLPackage document) throws Docx4JException, IOException {
        OutputStream out = getOutputStream();
        document.save(out);
        InputStream in = getInputStream(out);
        return WordprocessingMLPackage.load(in);
    }

    /**
     * Stamps the given template resolving the expressions within the template against the specified contextRoot.
     * Returns the resulting document after it has been saved and loaded again to ensure that changes in the Docx4j
     * object structure were really transported into the XML of the .docx file.
     */
    protected <T> WordprocessingMLPackage stampAndLoad(InputStream template, T contextRoot) throws IOException, Docx4JException {
        return stampAndLoad(template, contextRoot, new DocxStamperConfiguration());
    }

    protected <T> WordprocessingMLPackage stampAndLoad(InputStream template, T contextRoot, DocxStamperConfiguration config) throws IOException, Docx4JException {
        OutputStream out = getOutputStream();
        DocxStamper stamper = new DocxStamper(config);
        stamper.stamp(template, contextRoot, out);
        InputStream in = getInputStream(out);
        return WordprocessingMLPackage.load(in);
    }

    protected OutputStream getOutputStream() throws IOException {
        OutputStream out;
        if (Boolean.valueOf(System.getProperty("keepOutputFile"))) {
            tempFile = File.createTempFile(getClass().getSimpleName(), ".docx");
            logger.info(String.format(">>>>>>>> Saving DocxStamper output to temporary file %s <<<<<<<<", tempFile.getAbsolutePath()));
            out = new FileOutputStream(tempFile);
        } else {
            out = new ByteArrayOutputStream();
        }
        return out;
    }

    protected InputStream getInputStream(OutputStream out) throws FileNotFoundException {
        InputStream in;
        if (Boolean.valueOf(System.getProperty("keepOutputFile"))) {
            in = new FileInputStream(tempFile);

        } else {
            in = new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
        }
        return in;
    }

}


text:
"""Test the test support."""
from __future__ import absolute_import

import filecmp
import re
from os.path import join, isdir

from tests.lib import SRC_DIR

def test_tmp_dir_exists_in_env(script):
    """
    Test that $TMPDIR == env.temp_path and path exists and env.assert_no_temp()
    passes (in fast env)
    """
    # need these tests to ensure the assert_no_temp feature of scripttest is
    # working
    script.assert_no_temp()  # this fails if env.tmp_path doesn't exist
    assert script.environ['TMPDIR'] == script.temp_path
    assert isdir(script.temp_path)

def test_correct_pip_version(script):
    """
    Check we are running proper version of pip in run_pip.
    """
    # output is like:
    # pip PIPVERSION from PIPDIRECTORY (python PYVERSION)
    result = script.pip('--version')

    # compare the directory tree of the invoked pip with that of this source
    # distribution
    dir = re.match(
        r'pip \d(\.[\d])+(\.?(rc|dev|pre|post)\d+)? from (.*) '
        r'\(python \d(.[\d])+\)$',
        result.stdout
    ).group(4)
    pip_folder = join(SRC_DIR, 'pip')
    pip_folder_outputed = join(dir, 'pip')

    diffs = filecmp.dircmp(pip_folder, pip_folder_outputed)

    # If any non-matching .py files exist, we have a problem: run_pip
    # is picking up some other version!  N.B. if this project acquires
    # primary resources other than .py files, this code will need
    # maintenance
    mismatch_py = [
        x for x in diffs.left_only + diffs.right_only + diffs.diff_files
        if x.endswith('.py')
    ]
    assert not mismatch_py, (
        'mismatched source files in %r and %r: %r' %
        (pip_folder, pip_folder_outputed, mismatch_py)
    )

def test_as_import(script):
    """ test that pip.__init__.py does not shadow
    the command submodule with a dictionary
    """
    import pip.commands.install as inst
    assert inst is not None


text:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider(
    :auth0,
    ENV['AUTH0_CLIENT_ID'],
    ENV['AUTH0_CLIENT_SECRET'],
    ENV['AUTH0_DOMAIN'],
    callback_path: '/auth/oauth2/callback'
  )
end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Suriya Narayanan Lakshmanan is a Master's student at Carnegie Mellon University's
        Robotics Institute. He is studying Computer Vision">
        <meta name="author" content="Suriya Narayanan Lakshmanan">

        <title>Suriya Narayanan Lakshmanan - Computer Vision grad</title>

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

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

        <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
        <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

                    Digital art using SfM

                            Introduction

                            Work

                            Limitations

                            References

 Introduction

                The idea of this project is to create portrait effect from videos using Structure from motion and 3D segmentation

 Work

 Limitations

                    3D reconstruction is implemented in batch mode

                    Narrow baselines cause the SFM pipeline to fail


text:
Clone the repository and install the developer dependencies:

```
git clone git://github.com/unexpectedjs/unexpected.git unexpected
cd unexpected && npm install
```

## Source files

* *lib/index.js*:

  The entry point for the library.
* *lib/Unexpected.js*:

  The core of the library.
* *lib/Assertion.js*:

  The class that assertions are instantiated from.
* *lib/utils.js*:

  Utility functions
* *lib/styles.js*:

  MagicPen styles for controling the output.
* *lib/types.js*:

  Type definitions for every type Unexpected understands.
* *lib/assertions.js*:

  All assertions that is included in the core library.

## Running tests in the console

```
make test
make test-phantomjs
```

## Running tests in the browser

```
make test-browser
```

## Coverage report

```
make coverage
```

## Build a new release

Make sure that you have commited all changes before making the release.

The following make-targets will build the production version of _unexpected_,
commit the generated file and tag a new version using NPM.

### Patch release
make release patch

### Minor release
make release minor

### Major release
make release major


text:
module.exports = function(grunt) {
    "use strict";
    var peking = require('peking');
    var fs = require('fs');
    var gzip = require('gzip-js');

    // ## helper filesize
    // Get the combined filesize (including gzipped) of a collection of files.
    exports.filesize = function (files, cb) {
        // Keep track of the total numbe of bytes.
        var totalSize = 0;
        // Store all of the text we read from each file.
        var totalData;
        grunt.util.async.forEach(files, function(file, callback) {
            grunt.util.async.parallel([
                function(cb2) {
                    fs.stat(file, function(err, stat) {
                        if (err) {
                            cb2(err);
                        }
                        totalSize += stat.size;
                        cb2();
                    });
                },
                function(cb2) {
                    fs.readFile(file, function(err, data) {
                        if (err) {
                            cb2(err);
                        }
                        totalData += data;
                        cb2();
                    });
                }
                ], function(err, results) {
                    if (err) {
                        callback(err);
                    }
                    callback();
                });
        }, function(err) {
            if (err) {
                cb(err, null);
            }

            // Get compressed size of all of the files.
            var compressed = gzip.zip(totalData, {level: 6});

            cb(null, totalSize, compressed.length);
        });
    };

    // # multitask ducksboard
    // Send file size data of a collection of files to ducksboard
    grunt.registerMultiTask('ducksboard', 'Send file size data to ducksboard.', function() {
        var done = this.async(), task = this;
        this.requiresConfig('meta.ducksboard_api_key');
        var endpoint = this.data.endpoint;
        var gzip = this.data.gzip === true;
        if (!endpoint) {
            grunt.warn('Every target must specify an endpoint.');
        }

        var js = grunt.file.expand(this.filesSrc);
        exports.filesize(js, function(err, totalSize, compressedSize) {
            if (err) {
                grunt.warn(err);
            }
            grunt.log.writeln('[' + task.target + '] total size (bytes): ' + totalSize +
                ' compressed (bytes): ' + compressedSize);
            peking.pushValue({value: gzip ? compressedSize : totalSize,
                endpoint: endpoint, api_key: grunt.config('meta.ducksboard_api_key')}, function (err) {
                if (err) {
                    grunt.warn('Could not send data to ducksboard. Code ' + err + '.');
                }
                done();
            });
        });
    });
};


text:
module Representative

  class ObjectInspector

    def get_value(object, attribute_name)
      object.send(attribute_name)
    end

    def get_metadata(object, attribute_name)
      {}
    end

  end

end


text:
#ifndef KP_TRIPLE_SERI_HPP
#define KP_TRIPLE_SERI_HPP

#include <opencv2/opencv.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/vector.hpp>

#include "triple.hpp"

namespace boost {
    namespace serialization {

    template<class Archive, typename F, typename S, typename T>
    void serialize(Archive & ar, v4r::triple<F,S,T> &t, const unsigned int version)
    {
      ar & t.first;
      ar & t.second;
      ar & t.third;
    }

  }
}

#endif


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>SitRep1.0</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"></meta>

  <fieldset style="border: 5px groove threedface; margin: 2px; padding: 0.75em;">
  <legend>
      Login</legend>
<form action="javascript:srdLogin.connectToServer()" method="get">

             Select server:

  Username:

<input type="text" id="userbox" data-dojo-type="dojox.mobile.TextBox"></input>

  Password:

<input type="password" id="passbox" data-dojo-type="dojox.mobile.TextBox"></input>

<button type="submit" data-dojo-type="dojox.mobile.Button">
  Login</button>

   </form>
    </fieldset>

Edit Servers

About

  			SITREP

		THE OPEN SOURCE SOLUTION FOR PUBLIC SAFETY

	SitRep came to be because of the lack of easy to use tools for collaborative work on spatial and temporal data sets used for planning purposes in public safety. Development naturally progressed into an operational tool for the management of assets, and monitoring of events and as an analytical tool for after-action-reports because of the void of any tools that fulfilled these needs in public safety.

  <fieldset style="border: 5px groove threedface; margin: 2px; padding: 0.75em;">
  <legend>
      Edit</legend>

              Server:
         	<input type="text" id="editservername" data-dojo-type="dojox.mobile.TextBox"></input>

            City:	<input type="text" id="editcity" data-dojo-type="dojox.mobile.TextBox"></input>

            Username:	<input type="text" id="editusername" data-dojo-type="dojox.mobile.TextBox"></input>

         Password:	<input type="text" id="editpassword" data-dojo-type="dojox.mobile.TextBox"></input>

  				<button data-dojo-type="dojox.mobile.Button" id="savebutton" data-dojo-props="onClick:function(){srdLogin.saveserver();}">Save</button>


text:
As of the 3.0.0 release, this is now part of Maven Enforcer built-in rules as
[requireFileChecksum][2]. Use that, not this.

# Maven Enforcer Checksum Rule

This is a custom rule for the [maven-enforcer-plugin][1] to verify the checksum
of a file. To use in your project, add to your enforcer plugin configuration.
For example, to ensure that you have the correct Oracle JDBC 12.1.0.2 jars:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.4</version>
        <dependencies>
            <dependency>
                <groupId>ph.samson.maven</groupId>
                <artifactId>checksum-enforcer-rule</artifactId>
                <version>0.0.1</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
                <id>file-checksums</id>
                <goals>
                    <goal>enforce</goal>
                </goals>
                <configuration>
                    <rules>
                        <fileChecksum implementation="ph.samson.maven.enforcer.rule.checksum.FileChecksum">
                            <file>${oracle.dir}/ojdbc7.jar</file>
                            <checksum>7c9b5984b2c1e32e7c8cf3331df77f31e89e24c2</checksum>
                        </fileChecksum>
                        <fileChecksum implementation="ph.samson.maven.enforcer.rule.checksum.FileChecksum">
                            <file>${oracle.dir}/ucp.jar</file>
                            <checksum>ef4f2f99b07ee26673be62bbdccce78b0209042c</checksum>
                        </fileChecksum>
                    </rules>
                </configuration>
            </execution>
        </executions>
    </plugin>

By default, SHA1 is used. Set the `type` parameter to specify a different
algorithm. Possible values are:

* "crc32"
* "crc32c"
* "md5"
* "sha1"
* "sha256"
* "sha512"

[1]: https://maven.apache.org/enforcer/maven-enforcer-plugin/
[2]: https://maven.apache.org/enforcer/enforcer-rules/requireFileChecksum.html


text:
package com.github.nikdon.telepooz.model

import cats.Eq
import com.github.nikdon.telepooz.model.inline.AnswerInlineQuery
import com.github.nikdon.telepooz.model.methods._
import com.github.nikdon.telepooz.model.payments._

object EqInstances {
  implicit val eqAnimation: Eq[Animation]                       = Eq.fromUniversalEquals
  implicit val eqAudio: Eq[Audio]                               = Eq.fromUniversalEquals
  implicit val eqCallbackQuery: Eq[CallbackQuery]               = Eq.fromUniversalEquals
  implicit val eqChatMember: Eq[ChatMember]                     = Eq.fromUniversalEquals
  implicit val eqChat: Eq[Chat]                                 = Eq.fromUniversalEquals
  implicit val eqContact: Eq[Contact]                           = Eq.fromUniversalEquals
  implicit val eqDocument: Eq[Document]                         = Eq.fromUniversalEquals
  implicit val eqFile: Eq[File]                                 = Eq.fromUniversalEquals
  implicit val eqForceReply: Eq[ForceReply]                     = Eq.fromUniversalEquals
  implicit val eqGameHighScore: Eq[GameHighScore]               = Eq.fromUniversalEquals
  implicit val eqGame: Eq[Game]                                 = Eq.fromUniversalEquals
  implicit val eqInlineKeyboardButton: Eq[InlineKeyboardButton] = Eq.fromUniversalEquals
  implicit val eqInlineKeyboardMarkup: Eq[InlineKeyboardMarkup] = Eq.fromUniversalEquals
  implicit val eqKeyboardButton: Eq[KeyboardButton]             = Eq.fromUniversalEquals
  implicit val eqLocation: Eq[Location]                         = Eq.fromUniversalEquals
  implicit val eqMessageEntity: Eq[MessageEntity]               = Eq.fromUniversalEquals
  implicit val eqMessage: Eq[Message]                           = Eq.fromUniversalEquals
  implicit val eqPhotoSize: Eq[PhotoSize]                       = Eq.fromUniversalEquals
  implicit val eqReplyKeyboardHide: Eq[ReplyKeyboardHide]       = Eq.fromUniversalEquals
  implicit val eqReplyKeyboardMarkup: Eq[ReplyKeyboardMarkup]   = Eq.fromUniversalEquals
  implicit val eqSticker: Eq[Sticker]                           = Eq.fromUniversalEquals
  implicit val eqUpdate: Eq[Update]                             = Eq.fromUniversalEquals
  implicit val eqUserProfilePhotos: Eq[UserProfilePhotos]       = Eq.fromUniversalEquals
  implicit val eqUser: Eq[User]                                 = Eq.fromUniversalEquals
  implicit val eqVenue: Eq[Venue]                               = Eq.fromUniversalEquals
  implicit val eqVoice: Eq[Voice]                               = Eq.fromUniversalEquals
  implicit val eqVideo: Eq[Video]                               = Eq.fromUniversalEquals
  implicit val eqVideoNote: Eq[VideoNote]                       = Eq.fromUniversalEquals

  // Payments
  implicit val invoiceEq: Eq[Invoice]                     = Eq.fromUniversalEquals
  implicit val labeledPriceEq: Eq[LabeledPrice]           = Eq.fromUniversalEquals
  implicit val orderInfoEq: Eq[OrderInfo]                 = Eq.fromUniversalEquals
  implicit val preCheckoutQueryEq: Eq[PreCheckoutQuery]   = Eq.fromUniversalEquals
  implicit val shippingAddressEq: Eq[ShippingAddress]     = Eq.fromUniversalEquals
  implicit val shippingOptionEq: Eq[ShippingOption]       = Eq.fromUniversalEquals
  implicit val shippingQueryEq: Eq[ShippingQuery]         = Eq.fromUniversalEquals
  implicit val successfulPaymentEq: Eq[SuccessfulPayment] = Eq.fromUniversalEquals

  implicit val eqAnswerCallbackQuery: Eq[AnswerCallbackQuery]       = Eq.fromUniversalEquals
  implicit val eqEditMessageCaption: Eq[EditMessageCaption]         = Eq.fromUniversalEquals
  implicit val eqEditMessageReplyMarkup: Eq[EditMessageReplyMarkup] = Eq.fromUniversalEquals
  implicit val eqEditMessageText: Eq[EditMessageText]               = Eq.fromUniversalEquals
  implicit val eqForwardMessage: Eq[ForwardMessage]                 = Eq.fromUniversalEquals
  implicit val eqGetChatAdministrators: Eq[GetChatAdministrators]   = Eq.fromUniversalEquals
  implicit val eqGetChatMembersCount: Eq[GetChatMembersCount]       = Eq.fromUniversalEquals
  implicit val eqGetChatMember: Eq[GetChatMember]                   = Eq.fromUniversalEquals
  implicit val eqGetChat: Eq[GetChat]                               = Eq.fromUniversalEquals
  implicit val eqGetMe: Eq[GetMe.type]                              = Eq.fromUniversalEquals
  implicit val eqSendChatAction: Eq[SendChatAction]                 = Eq.fromUniversalEquals
  implicit val eqSendMessage: Eq[SendMessage]                       = Eq.fromUniversalEquals

  implicit val eqAnswerInlineQuery: Eq[AnswerInlineQuery] = Eq.fromUniversalEquals
}


text:
namespace NFugue.Staccato
{
    public interface IPreprocessorFunction
    {
        /// <summary>
        ///  Returns the names of this function, which are the same names that would
        /// be seen in the Staccato function call, e.g., "TRILL" for a trill function.
        /// The name of the function must be expressed in all capital letters.
        /// This method may return multiple names of a function to allow for abbreviations
        /// (e.g., TR or TRILL could both be legal names for the trill function)
        /// </summary>
        string[] GetNames();

        /// <summary>
        /// Returns a string that should be inserted into the Staccato string
        /// instead of the function which is being pre-processed.
        /// </summary>
        string Apply(string parameters, StaccatoParserContext context);
    }
}


text:
Small library to manage profitbricks.com virtual servers.

The following operations are supported:
 * Start
 * Stop (safe, issues shutdown command first)
 * Shutdown (safe, issues shutdown command to server before powering off)
 * Hard stop
 * Update cores and RAM based on configured 'profiles'
 * Get basic server status information (state, cores, RAM)
 * Run commands on groups of servers via custom configured groups
 * Operate on servers in different datacenters

Both a CLI executable and a Node.js library are provided.

## Installation
```
git clone https://github.com/thehunmonkgroup/pb-server.git
cd pb-server
npm install
cp config.sample.js config.js
```

Edit config.js to taste.

See [config.sample.js](config.sample.js) for a fully commented explanation of
the various configuration options.

## Usage

### CLI

#### For commands on individual (or groups of configured) servers.
Run ```pb``` without arguments for script usage.

The CLI executable supports configuring 'groups' in the config file which
allow commands to be run on multiple servers at once.

### As a node module.

```javascript
var PbServer = require('./pb-server');
var config = require('./config');
var pb = new PbServer(config.pb, config.ssh);

// Server labels are the keys as defined in config.js, 'servers' object.
var serverName = 'serverLabelOne';
var cb = function(err, data) {
  if (err) {
    console.log(format("ERROR: %s, %s", err, data));
  }
  console.log(data);
}
pb.getServer(serverName, cb);
```

See ```pb-server.js``` for all currently supported methods, and ```pb``` for more usage examples.

## Shell completion

The provided [pb.bash_completion](pb.bash_completion) can be used to enable
shell completion for BASH.

## Support

The issue tracker for this project is provided to file bug reports, feature
requests, and project tasks -- support requests are not accepted via the issue
tracker. For all support-related issues, including configuration, usage, and
training, consider hiring a competent consultant.


text:
    <button type="button" class="btn-pink" href="#" id="landing-get-started-button" rel="nofollow">Sign up</button>

    Already a member? Login


text:
require 'jamf/ruby_extensions/filetest/predicates'

module FileTest

  extend JamfRubyExtensions::FileTest::Predicates

end # module FileTest


text:
#include "tensorflow_serving/resources/resource_values.h"

namespace tensorflow {
namespace serving {

namespace device_types {
const char* const kMain = "main";
const char* const kGpu = "gpu";
}  // namespace device_types

namespace resource_kinds {
const char* const kNumModelSlots = "num_model_slots";
const char* const kRamBytes = "ram_in_bytes";
const char* const kProcessingMillis = "processing_in_millicores";
const char* const kP90LatencyMicros = "p90_latency_in_microseconds";
}  // namespace resource_kinds

}  // namespace serving
}  // namespace tensorflow


text:
using System;
using System.Collections.Generic;
using System.Text;

using wojilu.ORM;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;

using wojilu.Apps.Forum.Domain;
using wojilu.Common.Security;
using wojilu.Common.Money.Domain;
using wojilu.Web.Controller.Forum.Utils;
using wojilu.Members.Users.Domain;

namespace wojilu.Web.Controller.Forum {

    public partial class TopicListController : ControllerBase {

        private void bindAll( int boardId, List<ForumTopic> stickyList, DataPage<ForumTopic> topicList, List<ForumCategory> categories, Boolean isAdmin ) {

            int replySize = ((ForumApp)ctx.app.obj).GetSettingsObj().ReplySize;

            bindBoardInfo();

            bindCategories( boardId, categories );

            bindTopicList( stickyList, getBlock( "stickyList" ), isAdmin, true, replySize );

            bindTopicList( topicList.Results, getBlock( "postlist" ), isAdmin, false, replySize );

            // 分页和表单
            bindPagerAndForm( boardId, topicList );

            bindToolbar( topicList );

            bindAdminToolbar( isAdmin );
        }

        private void bindTopicList( List<ForumTopic> list, IBlock postBlock, Boolean isAdmin, Boolean isSticky, int replySize ) {
            if (list == null) return;
            foreach (ForumTopic topic in list) {
                bindTopicOne( postBlock, topic, isAdmin, isSticky, replySize );
            }
        }

        private void bindCategories( int id, List<ForumCategory> categories ) {

            IBlock panelBlock = getBlock( "categoryPanel" );
            if (categories.Count > 0) {

                IBlock block = panelBlock.GetBlock( "categories" );
                foreach (ForumCategory category in categories) {
                    block.Set( "c.Name", category.Name );
                    block.Set( "c.NameColor", category.NameColor );
                    block.Set( "c.LinkShow", to( new BoardController().Category, category.BoardId ) + "?categoryId=" + category.Id );
                    block.Next();
                }

                panelBlock.Set( "boardLink", to( new BoardController().Show, id ) );
                panelBlock.Next();
            }
        }

        private void bindToolbar( DataPage<ForumTopic> topicList ) {
            ctx.SetItem( "topicListPagebar", topicList.PageBar );
            String toolbarHtml = loadHtml( Toolbar );
            set( "toolbar", toolbarHtml );
            String toolbarBottomHtml = topicList.RecordCount > 10 ? toolbarHtml : "";
            set( "toolbarBottom", toolbarBottomHtml );
        }

        private void bindAdminToolbar( Boolean isAdmin ) {
            //String adminTool = isAdmin ? loadHtml( AdminToolbar ) : "";
            //set( "adminToolbar", adminTool );

            load( "adminToolbar", AdminToolbar );
        }

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

        private void bindBoardInfo() {

            set( "app.Url", ctx.app.Url );
            set( "forumBoard.Title", fb.Name );
            set( "forumBoard.Url", to( new BoardController().Show, fb.Id ) );

            set( "forumBoard.Notice", strUtil.HasText( fb.Notice ) ? alang( "notice" ) + ": " + fb.Notice : "" );
            set( "forumBoard.Moderator", moderatorService.GetModeratorHtml( fb ) );

            set( "moderatorJson", moderatorService.GetModeratorJson( fb ) );
        }

        private void bindTopicOne( IBlock block, ForumTopic topic, Boolean isAdmin, Boolean isSticky, int replySize ) {

            if (topic.Creator == null) return;

            String stickyIconName = topic.IsGlobalSticky ? "gsticky" : "sticky";
            if (isSticky) block.Set( "stickyIconName", stickyIconName );

            String rewardInfo = string.Empty;
            if (topic.Reward > 0) rewardInfo = getRewardInfo( topic, rewardInfo );

            String lblNew = string.Empty;
            ForumApp app = ctx.app.obj as ForumApp;
            int newDays = app.GetSettingsObj().NewDays;
            if (DateTime.Now.Subtract( topic.Created ).Days < newDays) lblNew = "new";

            String lblCategory = string.Empty;
            if (topic.Category != null && topic.Category.Id > 0) {
                String lnkCategory = to( new BoardController().Category, topic.ForumBoard.Id ) + "?categoryId=" + topic.Category.Id;
                lblCategory = string.Format( "[{1}] ", lnkCategory, topic.Category.Name, topic.Category.NameColor );
            }

            String typeImg = string.Empty;
            if (strUtil.HasText( topic.TypeName )) {
                typeImg = string.Format( "", sys.Path.Skin, topic.TypeName );
            }

            String priceInfo = string.Empty;
            if (topic.Price > 0) {
                priceInfo = alang( "price" ) + " :" + topic.Price + " ";
            }

            String permissionInfo = string.Empty;
            if (topic.ReadPermission > 0) {
                permissionInfo = alang( "readPermission" ) + ":" + topic.ReadPermission + "";
            }

            //String chkId = "";
            //if (isAdmin) chkId = "<input type=\"checkbox\" name=\"postSelect\" id=\"checkbox" + topic.Id + "\" value=\"" + topic.Id + "\" />";
            String chkId = "<input type=\"checkbox\" name=\"postSelect\" id=\"checkbox" + topic.Id + "\" value=\"" + topic.Id + "\" />";

            block.Set( "p.CheckBox", chkId );

            block.Set( "p.Id", topic.Id );
            block.Set( "p.Category", lblCategory );
            block.Set( "p.TypeImg", typeImg );
            block.Set( "p.Reward", rewardInfo );
            block.Set( "p.Price", priceInfo );
            block.Set( "p.ReadPermission", permissionInfo );
            block.Set( "p.Titile", strUtil.CutString( topic.Title, 40 ) );
            block.Set( "p.TitleStyle", topic.TitleStyle );
            block.Set( "p.LabelNew", lblNew );

            String lnk = LinkUtil.appendListPage( Link.To( new TopicController().Show, topic.Id ), ctx );

            block.Set( "p.Url", lnk );

            block.Set( "p.Pages", getPostPagesString( alink.ToAppData( topic ), topic.Replies, replySize ) );
            block.Set( "p.MemberName", topic.Creator.Name );
            block.Set( "p.MemberUrl", Link.ToMember( topic.Creator ) );
            block.Set( "p.CreateTime", topic.Created.ToShortDateString() );
            block.Set( "p.ReplyCount", topic.Replies );
            block.Set( "p.Hits", topic.Hits );
            block.Set( "p.LastUpdate", topic.Replied.GetDateTimeFormats( 'g' )[0] );
            block.Set( "p.LastReplyUrl", Link.ToUser( topic.RepliedUserFriendUrl ) );
            block.Set( "p.LastReplyName", topic.RepliedUserName );

            String attachments = topic.Attachments > 0 ? "" : "";
            block.Set( "p.Attachments", attachments );

            String statusImg;

            if (topic.IsLocked == 1)
                statusImg = sys.Path.Skin + "apps/forum/lock.gif";
            else if (topic.IsPicked == 1)
                statusImg = sys.Path.Skin + "apps/forum/pick.gif";
            else
                statusImg = sys.Path.Skin + "apps/forum/topic.gif";

            block.Set( "postStatusImage", statusImg );
            block.Next();
        }

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

        private void bindPagerAndForm( int id, DataPage<ForumTopic> topicList ) {

            IBlock formBlock = getBlock( "form" );

            List<ForumCategory> categories = categoryService.GetByBoard( id );
            if (categories.Count > 1) {
                categories.Insert( 0, new ForumCategory( 0, alang( "plsSelectCategory" ) ) );
            }

            bindFormNew( id, formBlock, categories );

        }

        private void bindFormNew( int boardId, IBlock formBlock, List<ForumCategory> categories ) {

            formBlock.Set( "ActionLink", Link.To( new Users.TopicController().Create ) + "?boardId=" + boardId );

            Editor ed = Editor.NewOne( "Content", "", "150px", sys.Path.Editor, MvcConfig.Instance.JsVersion, Editor.ToolbarType.Basic );
            ed.AddUploadUrl( ctx );

            formBlock.Set( "Editor", ed );

            formBlock.Set( "loginLink", t2( new MainController().Login ) );
            formBlock.Set( "regLink", t2( new RegisterController().Register ) );

            //User user = ctx.viewer.obj as User;
            //String userHtml = strUtil.HasText( user.Pic ) ? "" : user.Name;
            //formBlock.Set( "currentUser", userHtml );

            String categoryHtml = "";
            if (categories.Count > 0) categoryHtml = Html.DropList( categories, "CategoryId", "Name", "Id", 0 );
            formBlock.Set( "Category", categoryHtml );

            formBlock.Next();
        }

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

        private String getRewardInfo( ForumTopic topic, String rewardInfo ) {
            if (topic.RewardAvailable == 0) {
                rewardInfo = "(" + alang( "resolved" ) + ")";
            }
            else {
                rewardInfo = string.Format( "({0}{1})", topic.Reward, KeyCurrency.Instance.Unit );
            }
            if (DateTime.Now.Subtract( topic.Created ).Days >= ForumConfig.Instance.QuestionExpiryDay) {
            }
            return rewardInfo;
        }

        private String getPostPagesString( String url, int replies, int pageSize ) {

            if (replies < pageSize) return string.Empty;

            int beginsize = 5;
            int endsize = 1;
            int pcount = getPageCount( replies, pageSize );

            StringBuilder builder = new StringBuilder( "[ " );

            if (pcount <= (beginsize + endsize)) {
                for (int i = 1; i <= pcount; i++) {
                    appendLink( url, builder, i );
                }
            }
            else {
                int i = 1;
                while (i <= beginsize) {
                    appendLink( url, builder, i );
                    i++;
                }
                builder.Append( " .. " );
                for (i = endsize - 1; i >= 0; i--) {
                    int no = pcount - i;
                    appendLink( url, builder, no );
                }
            }
            builder.Append( " ]" );
            return builder.ToString();
        }

        private void appendLink( String url, StringBuilder builder, int i ) {
            builder.AppendFormat( "{1} ", LinkUtil.appendListPage( Link.AppendPage( url, i ), ctx ), i );
        }

        private static int getPageCount( int replies, int pageSize ) {

            int topicAndReplies = replies + 1;
            int mod = topicAndReplies % pageSize;
            if (mod == 0) {
                return (topicAndReplies / pageSize);
            }
            return ((topicAndReplies / pageSize) + 1);
        }

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

        [NonVisit]
        public void Toolbar() {

            int id = fb.Id;

            set( "slink", to( new BoardController().Show, id ) );
            set( "slinkReplied", to( new BoardController().Replied, id ) );
            set( "slinkCreated", to( new BoardController().Created, id ) );
            set( "slinkReplies", to( new BoardController().Replies, id ) );
            set( "slinkViews", to( new BoardController().Views, id ) );

            set( "slinkAll", to( new BoardController().All, id ) );
            set( "slinkDay", to( new BoardController().Day, id ) );
            set( "slinkDayTwo", to( new BoardController().DayTwo, id ) );
            set( "slinkWeek", to( new BoardController().Week, id ) );
            set( "slinkMonth", to( new BoardController().Month, id ) );
            set( "slinkMonthThree", to( new BoardController().MonthThree, id ) );
            set( "slinkMonthSix", to( new BoardController().MonthSix, id ) );

            set( "newPostUrl", Link.To( new Users.TopicController().NewTopic ) + "?boardId=" + id );
            set( "newPollUrl", Link.To( new Users.PollController().Add ) + "?boardId=" + id );
            set( "newQUrl", Link.To( new Users.TopicController().NewQ ) + "?boardId=" + id );
            set( "forumBoard.PollUrl", to( Polls, id ) );
            set( "forumBoard.PickedUrl", to( Picked, id ) );
            set( "page", ctx.GetItem( "topicListPagebar" ) );
        }

        [NonVisit]
        public void AdminToolbar() {

            int id = fb.Id;

            Moderators.TopicController t = new Forum.Moderators.TopicController();
            Moderators.TopicSaveController ts = new Forum.Moderators.TopicSaveController();

            set( "adminSticky", urlto( t.Sticky, id ) );
            set( "adminPicked", urlto( t.Picked, id ) );
            set( "adminHighlight", urlto( t.Highlight, id ) );
            set( "adminLock", urlto( t.Lock, id ) );

            set( "adminStickyUndo", urlto( ts.StickyUndo, id ) );
            set( "adminPickedUndo", urlto( ts.PickedUndo, id ) );
            set( "adminHighlightUndo", urlto( ts.HighlightUndo, id ) );
            set( "adminLockUndo", urlto( ts.LockUndo, id ) );
            set( "adminCategory", urlto( t.Category, id ) );
            set( "adminDelete", urlto( t.Delete, id ) );

            set( "stickyOrderLink", urlto( t.SortSticky, id ) );

            String cmdGsticky = string.Format( " {0}", alang( "cmdGlobalSticky" ) );
            String cmd = "{1}";
            String adminGlobalSticky = string.Format( cmd, urlto( t.GlobalSticky, id ), cmdGsticky );

            String gstickyOrderLink = urlto( t.GlobalSortSticky, id );
            adminGlobalSticky += " ›› " + alang( "pSortStickyTopic" ) + "";

            String gstickyUndoLink = urlto( ts.GlobalStickyUndo, id );
            String cmdPost = "{1}";
            String adminGlobalStickyUndo = string.Format( cmdPost, gstickyUndoLink, alang( "cmdGlobalStickyUndo" ) );

            String moveLink = urlto( t.Move, id );
            String adminMove = string.Format( cmd, moveLink, alang( "moveTopic" ) );

            set( "adminGsticky", adminGlobalSticky );
            set( "adminGstickyUndo", adminGlobalStickyUndo );
            set( "adminMove", adminMove );

        }

        private String urlto( aAction action, int id ) {
            return to( action ) + "?boardId=" + id;
        }

    }

}


text:
<configuration scan="true" scanPeriod="1 seconds" debug="false">

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="CONSOLE" />
  </root>

</configuration>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.Sql.Models;

namespace Microsoft.Azure.Management.Sql.Models
{
    /// <summary>
    /// Represents the properties of an Azure SQL Database.
    /// </summary>
    public partial class DatabaseProperties
    {
        private string _collation;

        /// <summary>
        /// Optional. Gets the collation of the Azure SQL Database.
        /// </summary>
        public string Collation
        {
            get { return this._collation; }
            set { this._collation = value; }
        }

        private DateTime _creationDate;

        /// <summary>
        /// Optional. Gets the creation date of the Azure SQL Database.
        /// </summary>
        public DateTime CreationDate
        {
            get { return this._creationDate; }
            set { this._creationDate = value; }
        }

        private string _currentServiceObjectiveId;

        /// <summary>
        /// Optional. Gets the current Service Level Objective Id of the Azure
        /// SQL Database. This is the Id of the Service Level Objective that
        /// is currently active.
        /// </summary>
        public string CurrentServiceObjectiveId
        {
            get { return this._currentServiceObjectiveId; }
            set { this._currentServiceObjectiveId = value; }
        }

        private string _databaseId;

        /// <summary>
        /// Optional. Gets the Id of the Azure SQL Database.
        /// </summary>
        public string DatabaseId
        {
            get { return this._databaseId; }
            set { this._databaseId = value; }
        }

        private DateTime _earliestRestoreDate;

        /// <summary>
        /// Optional. Gets the recovery period starte date of the Azure SQL
        /// Database. This records the start date and time when recovery is
        /// available for this Azure SQL Database.
        /// </summary>
        public DateTime EarliestRestoreDate
        {
            get { return this._earliestRestoreDate; }
            set { this._earliestRestoreDate = value; }
        }

        private string _edition;

        /// <summary>
        /// Optional. Gets the edition of the Azure SQL Database.  The
        /// DatabaseEditions enumeration contains all the valid editions.
        /// </summary>
        public string Edition
        {
            get { return this._edition; }
            set { this._edition = value; }
        }

        private string _elasticPoolName;

        /// <summary>
        /// Optional. Gets the name of the Azure SQL Database Elastic Pool the
        /// database is in.
        /// </summary>
        public string ElasticPoolName
        {
            get { return this._elasticPoolName; }
            set { this._elasticPoolName = value; }
        }

        private long _maxSizeBytes;

        /// <summary>
        /// Optional. Gets the max size of the Azure SQL Database expressed in
        /// bytes.
        /// </summary>
        public long MaxSizeBytes
        {
            get { return this._maxSizeBytes; }
            set { this._maxSizeBytes = value; }
        }

        private string _requestedServiceObjectiveId;

        /// <summary>
        /// Optional. Gets the configured Service Level Objective Id of the
        /// Azure SQL Database. This is the Service Level Objective that is
        /// being applied to the Azure SQL Database.
        /// </summary>
        public string RequestedServiceObjectiveId
        {
            get { return this._requestedServiceObjectiveId; }
            set { this._requestedServiceObjectiveId = value; }
        }

        private string _requestedServiceObjectiveName;

        /// <summary>
        /// Optional. Gets the name of the configured Service Level Objective
        /// of the Azure SQL Database. This is the Service Level Objective
        /// that is being applied to the Azure SQL Database.
        /// </summary>
        public string RequestedServiceObjectiveName
        {
            get { return this._requestedServiceObjectiveName; }
            set { this._requestedServiceObjectiveName = value; }
        }

        private string _serviceObjective;

        /// <summary>
        /// Optional. Gets the Service Level Objective of the Azure SQL
        /// Database.
        /// </summary>
        public string ServiceObjective
        {
            get { return this._serviceObjective; }
            set { this._serviceObjective = value; }
        }

        private IList<ServiceTierAdvisor> _serviceTierAdvisors;

        /// <summary>
        /// Optional. Gets the list of service tier advisors for this database.
        /// Expanded property
        /// </summary>
        public IList<ServiceTierAdvisor> ServiceTierAdvisors
        {
            get { return this._serviceTierAdvisors; }
            set { this._serviceTierAdvisors = value; }
        }

        private string _status;

        /// <summary>
        /// Optional. Gets the status of the Azure SQL Database.
        /// </summary>
        public string Status
        {
            get { return this._status; }
            set { this._status = value; }
        }

        private UpgradeHint _upgradeHint;

        /// <summary>
        /// Optional. Gets the upgrade hint for this database.
        /// </summary>
        public UpgradeHint UpgradeHint
        {
            get { return this._upgradeHint; }
            set { this._upgradeHint = value; }
        }

        /// <summary>
        /// Initializes a new instance of the DatabaseProperties class.
        /// </summary>
        public DatabaseProperties()
        {
            this.ServiceTierAdvisors = new LazyList<ServiceTierAdvisor>();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Michelia (1880)

#### Original name
null

### Remarks
null


text:
using System.Collections.Generic;
using Orchard.AuditTrail.Services;
using Orchard.Environment.Extensions;
using Orchard.Security;
using Orchard.Users.Events;

namespace Orchard.AuditTrail.Providers.Users {
    [OrchardFeature("Orchard.AuditTrail.Users")]
    public class UserEventHandler : IUserEventHandler {
        private readonly IAuditTrailManager _auditTrailManager;
        private readonly IWorkContextAccessor _wca;

        public UserEventHandler(IAuditTrailManager auditTrailManager, IWorkContextAccessor wca) {
            _auditTrailManager = auditTrailManager;
            _wca = wca;
        }

        public void LoggedIn(IUser user) {
            RecordAuditTrail(UserAuditTrailEventProvider.LoggedIn, user);
        }

        public void LoggedOut(IUser user) {
            RecordAuditTrail(UserAuditTrailEventProvider.LoggedOut, user);
        }

        public void LogInFailed(string userNameOrEmail, string password) {
            var eventData = new Dictionary<string, object> {
                {"UserName", userNameOrEmail}
            };

            _auditTrailManager.CreateRecord<UserAuditTrailEventProvider>(UserAuditTrailEventProvider.LogInFailed, _wca.GetContext().CurrentUser, properties: null, eventData: eventData, eventFilterKey: "user", eventFilterData: userNameOrEmail);
        }

        public void ChangedPassword(IUser user, string password) {
            RecordAuditTrail(UserAuditTrailEventProvider.PasswordChanged, user);
        }

        private void RecordAuditTrail(string eventName, IUser user) {

            var properties = new Dictionary<string, object> {
                {"User", user}
            };

            var eventData = new Dictionary<string, object> {
                {"UserId", user.Id},
                {"UserName", user.UserName}
            };

            _auditTrailManager.CreateRecord<UserAuditTrailEventProvider>(eventName, _wca.GetContext().CurrentUser, properties, eventData, eventFilterKey: "user", eventFilterData: user.UserName);
        }

        public void Creating(UserContext context) {
        }

        public void Created(UserContext context) {
        }

        public void LoggingIn(string userNameOrEmail, string password) {
        }

        public void AccessDenied(IUser user) {
        }

        public void SentChallengeEmail(IUser user) {
        }

        public void ConfirmedEmail(IUser user) {
        }

        public void Approved(IUser user) {
        }

        public void Moderate(IUser user) {
        }
    }
}


text:
package core.dependencies

object MavenDependencyScope extends Enumeration {
  val Provided = Value("provided")
  val Compile = Value("compile")
  val Runtime = Value("runtime")
  val Import = Value("import")
  val Test = Value("test")
}


text:
<?php

declare (strict_types=1);
namespace Rector\DowngradePhp71\Rector\TryCatch;

use PhpParser\Node;
use PhpParser\Node\Stmt\Catch_;
use PhpParser\Node\Stmt\TryCatch;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @see \Rector\Tests\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector\DowngradePipeToMultiCatchExceptionRectorTest
 */
final class DowngradePipeToMultiCatchExceptionRector extends \Rector\Core\Rector\AbstractRector
{
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Downgrade single one | separated to multi catch exception', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
try {
    // Some code...
 } catch (ExceptionType1 | ExceptionType2 $exception) {
    $sameCode;
 }
CODE_SAMPLE
, <<<'CODE_SAMPLE'
try {
    // Some code...
} catch (ExceptionType1 $exception) {
    $sameCode;
} catch (ExceptionType2 $exception) {
    $sameCode;
}
CODE_SAMPLE
)]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Stmt\TryCatch::class];
    }
    /**
     * @param TryCatch $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        $originalCatches = $node->catches;
        foreach ($node->catches as $key => $catch) {
            if (\count($catch->types) === 1) {
                continue;
            }
            $types = $catch->types;
            $node->catches[$key]->types = [$catch->types[0]];
            foreach ($types as $keyCatchType => $catchType) {
                if ($keyCatchType === 0) {
                    continue;
                }
                $this->addNodeAfterNode(new \PhpParser\Node\Stmt\Catch_([$catchType], $catch->var, $catch->stmts), $node->catches[$key]);
            }
        }
        if ($this->nodeComparator->areNodesEqual($originalCatches, $node->catches)) {
            return null;
        }
        return $node;
    }
}


text:
module Snap.Snaplet.HTTPAuth.Backend (
    AllowEverythingIfHeader (..),
    UserPass (..)
) where

import Snap.Snaplet.HTTPAuth.Backend.AllowEverythingIfHeader
import Snap.Snaplet.HTTPAuth.Backend.UserPass


text:
namespace irr
{
namespace gui
{

class IGUIScrollBar;
class IGUITab;

enum E_SCROLL_BAR_MODE
{
	//! The scrollbar will only show up when needed.
	ESBM_AUTOMATIC = 0,

	//! The scrollbar will never be visible.
	ESBM_ALWAYS_INVISIBLE,

	//! The scrollbar will always the visible.
	ESBM_ALWAYS_VISIBLE,

	//! just a count of how many are in this enum
	ESBM_COUNT
};

const c8* const GUIScrollBarModeNames[] =
{
	"automatic",
	"alwaysInvisible",
	"alwaysVisible",
	0
};

class CGUIPanel : public IGUIElement
{
public:
	CGUIPanel( IGUIEnvironment* environment, IGUIElement* parent, s32 id=-1,
			const core::rect<s32>& rectangle = core::rect<s32>(0,0,100,100),
			bool border=false,
			E_SCROLL_BAR_MODE vMode=ESBM_AUTOMATIC,
			E_SCROLL_BAR_MODE hMode=ESBM_ALWAYS_INVISIBLE );

	virtual ~CGUIPanel();

	//! draws the panel and its children
	virtual void draw();

	//! returns true if it has a border, false if not
	bool hasBorder() const;

	//! sets whether the element draws a border
	void setBorder(bool enabled);

	//! returns a pointer to the vertical scrollbar
	IGUIScrollBar* getVScrollBar() const;

	//! returns a pointer to the horizontal scrollbar
	IGUIScrollBar* getHScrollBar() const;

	//! returns the vertical scrollbar visibility rule
	E_SCROLL_BAR_MODE getVScrollBarMode() const;

	//! sets the vertical scrollbar visibility rule
	void setVScrollBarMode(E_SCROLL_BAR_MODE mode);

	//! returns the horizontal scrollbar visibility rule
	E_SCROLL_BAR_MODE getHScrollBarMode() const;

	//! sets the horizontal scrollbar visibility rule
	void setHScrollBarMode(E_SCROLL_BAR_MODE mode);

	//! returns the visible area inside the panel, excluding scrollbar and border
	core::rect<s32> getClientArea() const;

	virtual bool OnEvent(const SEvent &event);

	//! adds a child to the panel
	virtual void addChild(IGUIElement* child);

	//! removes a child from the panel
	virtual void removeChild(IGUIElement* child);

	//! updates the absolute position
	virtual void updateAbsolutePosition();

	//! returns children of the inner pane
	virtual const core::list<IGUIElement*>& getChildren();

	//! Returns the type name of the gui element.
	virtual const c8* getTypeName() const
	{
		return GUIEditElementTypeNames[EGUIEDIT_GUIPANEL];
	}

	virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0);
	virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0);

protected:
	void moveInnerPane();
	void resizeInnerPane();
	void calculateClientArea();

private:

	IGUIScrollBar*	VScrollBar;
	IGUIScrollBar*	HScrollBar;
	IGUITab*	ClipPane;
	IGUITab*	InnerPane;

	E_SCROLL_BAR_MODE VScrollBarMode;
	E_SCROLL_BAR_MODE HScrollBarMode;

	bool NeedsUpdate;
	bool Border;
};

} // namespace gui
} // namespace irr

#endif


text:
package SynthLang.editor;

/*Generated by MPS */

import jetbrains.mps.openapi.editor.descriptor.ConceptEditorComponent;
import java.util.Collection;
import java.util.Collections;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.baseLanguage.editor.BaseLanguageStyle_StyleSheet;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.editor.runtime.style.StyleAttributes;

public class PanelParameters_component implements ConceptEditorComponent {
  public Collection<String> getContextHints() {
    return Collections.emptyList();
  }
  public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
    return this.createCollection_1z9852_a(editorContext, node);
  }
  private EditorCell createCollection_1z9852_a(EditorContext editorContext, SNode node) {
    EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node);
    editorCell.setCellId("Collection_1z9852_a");
    editorCell.addEditorCell(this.createConstant_1z9852_a0(editorContext, node));
    editorCell.addEditorCell(this.createConstant_1z9852_b0(editorContext, node));
    editorCell.addEditorCell(this.createProperty_1z9852_c0(editorContext, node));
    editorCell.addEditorCell(this.createConstant_1z9852_d0(editorContext, node));
    editorCell.addEditorCell(this.createConstant_1z9852_e0(editorContext, node));
    editorCell.addEditorCell(this.createProperty_1z9852_f0(editorContext, node));
    return editorCell;
  }
  private EditorCell createConstant_1z9852_a0(EditorContext editorContext, SNode node) {
    EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "panel size:");
    editorCell.setCellId("Constant_1z9852_a0");
    Style style = new StyleImpl();
    BaseLanguageStyle_StyleSheet.apply_Label(style, editorCell);
    editorCell.getStyle().putAll(style);
    editorCell.setDefaultText("");
    return editorCell;
  }
  private EditorCell createConstant_1z9852_b0(EditorContext editorContext, SNode node) {
    EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "columns");
    editorCell.setCellId("Constant_1z9852_b0");
    editorCell.setDefaultText("");
    return editorCell;
  }
  private EditorCell createProperty_1z9852_c0(EditorContext editorContext, SNode node) {
    CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
    provider.setRole("columns");
    provider.setNoTargetText("<no columns>");
    EditorCell editorCell;
    editorCell = provider.createEditorCell(editorContext);
    editorCell.setCellId("PP_property_columns");
    Style style = new StyleImpl();
    BaseLanguageStyle_StyleSheet.apply_NumericLiteral(style, editorCell);
    editorCell.getStyle().putAll(style);
    editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
    SNode attributeConcept = provider.getRoleAttribute();
    Class attributeKind = provider.getRoleAttributeClass();
    if (attributeConcept != null) {
      EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
      return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
    } else
    return editorCell;
  }
  private EditorCell createConstant_1z9852_d0(EditorContext editorContext, SNode node) {
    EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ",");
    editorCell.setCellId("Constant_1z9852_d0");
    editorCell.setDefaultText("");
    return editorCell;
  }
  private EditorCell createConstant_1z9852_e0(EditorContext editorContext, SNode node) {
    EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "rows");
    editorCell.setCellId("Constant_1z9852_e0");
    editorCell.setDefaultText("");
    return editorCell;
  }
  private EditorCell createProperty_1z9852_f0(EditorContext editorContext, SNode node) {
    CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
    provider.setRole("rows");
    provider.setNoTargetText("<no rows>");
    EditorCell editorCell;
    editorCell = provider.createEditorCell(editorContext);
    editorCell.setCellId("PP_property_rows");
    Style style = new StyleImpl();
    BaseLanguageStyle_StyleSheet.apply_NumericLiteral(style, editorCell);
    style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, 0, true);
    editorCell.getStyle().putAll(style);
    editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
    SNode attributeConcept = provider.getRoleAttribute();
    Class attributeKind = provider.getRoleAttributeClass();
    if (attributeConcept != null) {
      EditorManager manager = EditorManager.getInstanceFromContext(editorContext);
      return manager.createNodeRoleAttributeCell(attributeConcept, attributeKind, editorCell);
    } else
    return editorCell;
  }
}


text:
Project website: http://oscommerce.com

Version: 2.3.4

To build:

	turbo build -n=oscommerce /path/to/turbo.me


text:
layout: master
include: activity
name: Tryggve1
type: Project
leader: antti-pursula
phase: Finished
start: 2014-10-21
end: 2017-10-21
finished: yes
results: https://wiki.neic.no/wiki/Tryggve_Reports_and_Materials
outreach: N/A
outcome-statements:
documents:
  - text: Project plan
    url: https://wiki.neic.no/wiki/File:Tryggve_Project_Plan_approved_Nov-2014.pdf
  - text: Collaboration agreement
    url: https://wiki.neic.no/wiki/File:Tryggve_collaboration_agreement.pdf
links:
  - text: Tryggve
    url: ../tryggve
    description: Tryggve Nordic sensitive data program homepage.
  - text: Newsletters
    url: https://wiki.neic.no/wiki/Tryggve_News
  - text: External wiki
    url: https://wiki.neic.no/Tryggve
    description: Documentation, manuals and guides.
  - text: Internal wiki
    url: https://wiki.neic.no/int/Tryggve
    description: Internal working documents.
groups:
  tryggve1:
    name: Team
    minutes: https://wiki.neic.no/int/Category:Tryggve_project_group_meetings
    frequency: Weekly
  tryggve1-rg:
    name: Reference group
    description: Stakeholder engagement forum. Requirements gathering, outreach and quality assurance.
    frequency: 3-4 per year
    minutes: https://wiki.neic.no/wiki/Category:Tryggve_reference_group_meetings
  tryggve1-sg:
    name: Steering group
    description: The Nordic ELIXIR nodes and NeIC.
    frequency: 3-4 per year
    minutes: https://wiki.neic.no/wiki/Category:Tryggve_steering_group_meetings
  tryggve1-po:
    name: Project office
    description: Management.
    minutes: https://wiki.neic.no/int/Category:Tryggve_management_meetings
    frequency: Weekly
---
This page holds administrative information on the Tryggve1 project - the first
project in NeIC's collaboration with Nordic nodes of ELIXIR to facilitate
research on Nordic sensitive biomedical data.

For most information on Tryggve, [please see the Tryggve page](../tryggve).


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bearsoft.gui.grid.selection;

import com.bearsoft.gui.grid.GridTest;
import com.bearsoft.gui.grid.insets.LinearInset;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Gala
 */
public class ConstraintedSelectionTest extends GridTest {

    @Test
    public void changeConstrainedSelectionTest() throws Exception {
        int fixedRows = 2;
        int fixedCols = 3;
        // insets setup
        LinearInset rowsInset = new LinearInset(3, 7);
        LinearInset columnsInset = new LinearInset(2, 5);
        ConfResult conf = beginVisual(fixedRows, fixedCols, rowsInset, columnsInset);
        insettedColumnSelectionModel.setSelectionInterval(0, insettedColumnModel.getColumnCount() - 1);
        insettedSelectionModel.setSelectionInterval(0, 0);
        insettedColumnSelectionModel.setSelectionInterval(1, 1);
        insettedColumnSelectionModel.setSelectionInterval(0, 0);
        assertTrue(conf.tlTable.getSelectionModel().isSelectedIndex(0));
        assertTrue(conf.tlTable.getColumnModel().getSelectionModel().isSelectedIndex(0));
        endVisual();
    }

    @Test
    public void constraintedOverInsettedSelectionTest() throws Exception {
        int fixedRows = 2;
        int fixedCols = 3;
        // insets setup
        LinearInset rowsInset = new LinearInset(3, 7);
        LinearInset columnsInset = new LinearInset(2, 5);
        ConfResult conf = beginVisual(fixedRows, fixedCols, rowsInset, columnsInset);
        insettedColumnSelectionModel.setSelectionInterval(0, insettedColumnModel.getColumnCount() - 1);
        insettedSelectionModel.setSelectionInterval(0, 1);
        for (int i = 0; i < columnsInset.getPreFirst(); i++) {
            assertTrue(conf.tlTable.getColumnModel().getSelectionModel().isSelectedIndex(i));
            assertTrue(conf.tlTable.getSelectionModel().isSelectedIndex(0));
            assertTrue(conf.tlTable.getSelectionModel().isSelectedIndex(1));
        }
        for (int i = 0; i < conf.trTable.getColumnCount(); i++) {
            assertTrue(conf.trTable.getColumnModel().getSelectionModel().isSelectedIndex(i));
            assertTrue(conf.trTable.getSelectionModel().isSelectedIndex(0));
            assertTrue(conf.trTable.getSelectionModel().isSelectedIndex(1));
        }
        endVisual();
    }
    protected int columnSelectionEventsCount = 0;
    protected int columnSelectionEventsCount1 = 0;

    @Test
    public void constraintedColumnsSelection2ColumnModelEventsChainTest() throws Exception {
        columnSelectionEventsCount = 0;
        int fixedRows = 2;
        int fixedCols = 3;
        // insets setup
        LinearInset rowsInset = new LinearInset(3, 7);
        LinearInset columnsInset = new LinearInset(2, 5);
        ConfResult conf = beginVisual(fixedRows, fixedCols, rowsInset, columnsInset);
        insettedColumnSelectionModel.setSelectionInterval(0, insettedColumnModel.getColumnCount() - 1);
        insettedSelectionModel.setSelectionInterval(0, 0);
        insettedColumnSelectionModel.setSelectionInterval(1, 1);
        insettedColumnSelectionModel.setSelectionInterval(0, 0);
        assertTrue(conf.tlTable.getSelectionModel().isSelectedIndex(0));
        assertTrue(conf.tlTable.getColumnModel().getSelectionModel().isSelectedIndex(0));
        conf.tlTable.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

            public void columnAdded(TableColumnModelEvent e) {
            }

            public void columnRemoved(TableColumnModelEvent e) {
            }

            public void columnMoved(TableColumnModelEvent e) {
            }

            public void columnMarginChanged(ChangeEvent e) {
            }

            public void columnSelectionChanged(ListSelectionEvent e) {
                columnSelectionEventsCount++;
            }
        });
        insettedColumnSelectionModel.setSelectionInterval(1, 1);
        insettedColumnSelectionModel.setSelectionInterval(0, 0);
        assertEquals(4, columnSelectionEventsCount);
        endVisual();
    }
    @Test
    public void insettedColumnsSelection2ColumnModelEventsChainTest() throws Exception {
        columnSelectionEventsCount1 = 0;
        int fixedRows = 2;
        int fixedCols = 3;
        // insets setup
        LinearInset rowsInset = new LinearInset(3, 7);
        LinearInset columnsInset = new LinearInset(2, 5);
        ConfResult conf = beginVisual(fixedRows, fixedCols, rowsInset, columnsInset);
        insettedColumnSelectionModel.setSelectionInterval(0, insettedColumnModel.getColumnCount() - 1);
        insettedSelectionModel.setSelectionInterval(0, 0);
        insettedColumnSelectionModel.setSelectionInterval(1, 1);
        insettedColumnSelectionModel.setSelectionInterval(0, 0);
        assertTrue(conf.tlTable.getSelectionModel().isSelectedIndex(0));
        assertTrue(conf.tlTable.getColumnModel().getSelectionModel().isSelectedIndex(0));
        insettedColumnModel.addColumnModelListener(new TableColumnModelListener() {

            public void columnAdded(TableColumnModelEvent e) {
            }

            public void columnRemoved(TableColumnModelEvent e) {
            }

            public void columnMoved(TableColumnModelEvent e) {
            }

            public void columnMarginChanged(ChangeEvent e) {
            }

            public void columnSelectionChanged(ListSelectionEvent e) {
                columnSelectionEventsCount1++;
            }
        });
        insettedColumnSelectionModel.setSelectionInterval(1, 1);
        insettedColumnSelectionModel.setSelectionInterval(0, 0);
        assertEquals(2, columnSelectionEventsCount1);
        endVisual();
    }
}


text:
require 'test_helper'

class PasswordResetsTest < ActionDispatch::IntegrationTest

  def setup
    ActionMailer::Base.deliveries.clear
    @user = users(:michael)
  end

  test "password resets" do
    get new_password_reset_path
    assert_template 'password_resets/new'

    post password_resets_path, password_reset: { email: "" }
    assert_not flash.empty?
    assert_template 'password_resets/new'

    post password_resets_path, password_reset: { email: @user.email }
    assert_not_equal @user.reset_digest, @user.reload.reset_digest
    assert_equal 1, ActionMailer::Base.deliveries.size
    assert_not flash.empty?
    assert_redirected_to root_url

    user = assigns(:user)

    get edit_password_reset_path(user.reset_token, email: "")
    assert_redirected_to root_url

    user.toggle!(:activated)
    get edit_password_reset_path(user.reset_token, email: user.email)
    assert_redirected_to root_url
    user.toggle!(:activated)

    get edit_password_reset_path('wrong token', email: user.email)
    assert_redirected_to root_url

    get edit_password_reset_path(user.reset_token, email: user.email)
    assert_template 'password_resets/edit'
    assert_select "input[name=email][type=hidden][value=?]", user.email

    patch password_reset_path(user.reset_token),
          email: user.email,
          user: { password:              "foobaz",
                  password_confirmation: "barquux" }
    assert_select 'div#error_explanation'

    patch password_reset_path(user.reset_token),
          email: user.email,
          user: { password:              "",
                  password_confirmation: "" }
    assert_select 'div#error_explanation'

    patch password_reset_path(user.reset_token),
          email: user.email,
          user: { password:              "foobaz",
                  password_confirmation: "foobaz" }
    assert is_logged_in?
    assert_not flash.empty?
    assert_redirected_to user
  end

  test "expired token" do
    get new_password_reset_path
    post password_resets_path, password_reset: { email: @user.email }

    @user = assigns(:user)
    @user.update_attribute(:reset_sent_at, 3.hours.ago)
    patch password_reset_path(@user.reset_token),
          email: @user.email,
          user: { password: "foobar",
                  password_confirmation: "foobar" }
    assert_response :redirect
    follow_redirect!
    assert_match /expired/i, response.body
  end
end


text:
layout: post
title: Bagaimana Membatalkan Commit Git Sebelumnya
---
Pertanyaan ini muncul tatkala teman saya belum menyelesaikan keterangan commitnya tapi keburu salah tekan tombol enter yang menyebabkan commitnya berjalan.

Apa yang harus dilakukan ? agar commit terakhirnya bisa dibatalkan atau di undo ?

Saya menemukan jawaban yang bagus disini: [https://stackoverflow.com/questions/927358/how-do-i-undo-the-last-commits-in-git][1]{: rel="nofollow"}

```bash
git reset HEAD~
git add .
git commit -u "your commit"
```

Selain menggunakan cara reset, kita bisa menggunakan cara manual yaitu dengan perintah :

```bash
git commit --amend
```

Perintah ini akan membuka text editor default git yaitu *Vi*, jika anda tidak ingin menggunakan *Vi*, silahkan mengubah config core.editornya. Caranya ?

Contohnya kita akan menjadikan Sublime Text sebagai text editor default :

di Windows silahkan gunakan perintah berikut :
```bash
git config --global core.editor "'c:/program files/sublime text 3/subl.exe' -w"
```

di Mac or Linux bisa pake perintah ini :
```bash
git config --global core.editor "subl -n -w"
```

Nah, setelah terbuka, perhatikan pada baris pertama. Ubahlah nama commitnya. Selesai, simpan. Kemudian cek dengan `git log --oneline` maka hasilnya nama commitnya beruabh.

[1]: https://stackoverflow.com/questions/927358/how-do-i-undo-the-last-commits-in-git


text:
var members = require('../data/members'),
	questions = require('../data/questions'),
	projects = require('../data/projects'),
	jsonResponseHandler = require('../lib/jsonResponseHandler');

var utils = {};

// **************************************************************************
// Projects ****************************************************************
// **************************************************************************

function work(req, res) {
	projects.getProjects(function (err, _projects) {
		if (err) { jsonResponseHandler.BadResponse(err, req, res); }
		res.render('work', { title: 'Work', projects : _projects });
	})
}

function postProject(req, res) {
	if (req.body.name) {
		projects.addProject(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ mesasge: "Missing Data"}, req, res);
	}
}

function putProject(req, res) {
	if (req.body._id !== null && req.body._id !== undefined) {
		projects.updateQuestion(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ userError: true, mesasge: "Missing Data"}, req, res);
	}
}

// **************************************************************************
// MEMBERS ******************************************************************
// **************************************************************************

function team(req, res){
	members.getMembers(function(err, members) {
		if (err) { jsonResponseHandler.BadResponse(err, req, res); }
		res.render('team', { title: 'Team', members: members });
	});
};

function postMember(req, res) {
	if (req.body.name !== null && req.body.name !== undefined) {
		members.addTeamMember(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ mesasge: "Missing Data" }, req, res);
	}
};

function putMember(req, res) {
	if (req.body._id !== null && req.body._id !== undefined) {
		members.updateTeamMember(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ mesasge: "Missing Data" }, req, res);
	}
};

// **************************************************************************
// QUESTIONS ****************************************************************
// **************************************************************************

function postQuestion(req, res) {
	if (req.body.question !== null && req.body.question !== undefined) {
		questions.addQuestion(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ mesasge: "Missing Data"}, req, res);
	}
};

function putQuestion(req, res) {
	if (req.body._id !== null && req.body._id !== undefined) {
		questions.updateQuestion(req.body, function (err) {
			jsonResponseHandler.Json_Response(err, req, res);
		});
	} else {
		jsonResponseHandler.BadResponse({ userError: true, mesasge: "Missing Data"}, req, res);
	}
};

utils = {
	work : work,
	team : team,
	postProject : postProject,
	putProject : putProject,
	postMember : postMember,
	putMember : postMember,
	postQuestion : postQuestion,
	putQuestion : putQuestion
}

module.exports = utils;


text:
#ifndef __LAMBDA_HPP__
#define __LAMBDA_HPP__

#include <tr1/functional>

namespace lambda {

using std::tr1::bind;
using std::tr1::function;
using namespace std::tr1::placeholders;

} // namespace lambda {

#endif // __LAMBDA_HPP__


text:
package co.yiiu.config;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class OAuth2 {
  private String clientId;
  private String clientSecret;
  private String callbackUrl;
}