text:
#include <Thor/Framework/FileSystem/ThiFileSystem.h>
#include <Thor/Framework/FileSystem/ThiDataStream.h>
#include <Thor/Framework/FileSystem/ThiFileStream.h>
#include <Thor/Framework/FileSystem/ThiMemoryStream.h>
#include <Thor/Framework/FileSystem/FSExceptions.h>
#include <Thor/Framework/FileSystem/LoggerFileOutput.h>
#include <Thor/Framework/Singleton.h>

namespace Thor
{
//----------------------------------------------------------------------------------------
//
//					eFileSystemType
//
//----------------------------------------------------------------------------------------
struct eFileSystemType
{
	enum Val
	{
		PhysFS,
		BoostFS
	};
};
//----------------------------------------------------------------------------------------
//
//					ThFileSystemFactory
//
//----------------------------------------------------------------------------------------
class THOR_FRAMEWORK_DLL ThFileSystemFactory:public NonCopyable
{
public:
	ThiFileSystemPtr CreateFileSystem(eFileSystemType::Val type);

	static ThFileSystemFactory& Instance();
protected:

	friend class Singleton<ThFileSystemFactory>;
	typedef Singleton<ThFileSystemFactory> singleton_t;

	ThFileSystemFactory();
};

}//Thor
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>spring-cloud-starter-stream-processor-tcp-client</artifactId>
	<packaging>jar</packaging>
	<name>spring-cloud-starter-stream-processor-tcp-client</name>
	<description>Spring Cloud Stream tcp client processor</description>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>spring-cloud-stream-tcp-parent</artifactId>
		<version>1.1.0.BUILD-SNAPSHOT</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud.stream.app</groupId>
			<artifactId>app-starters-tcp-common</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud.stream.app</groupId>
			<artifactId>app-starters-test-support</artifactId>
		</dependency>
	</dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
##Javascript

###defer-image-load.js

By default, the `defer-image-load.js` script is not loaded in the theme. You'll need to add the script within the `<head>` tag.

####Usage

```
<img data-defer-src="/path/to/image.png" width="300" height="300" alt="Deferred Image" />
```

###mhc.slideshow.js

The mhc slideshow will be replaced with [Gallery CSS](https://github.com/benschwarz/gallery-css/) in the upcoming 0.9.4 release.

###simplebox.js

The mhc modal will be replaced with [CSS Modal](https://github.com/drublic/css-modal) in the upcoming 0.9.4 release.


text:
/** Added to outer field elements to hide them **/
.alpaca-hidden
{
    display: none;
}

/** Added to every field outer element **/
.alpaca-field
{

}

/** Added to every container outer field element **/
.alpaca-container
{

}

/** Added to the optional label (or legend) accompanying any container **/
.alpaca-container-label
{

}

/** Added to every container item field within a container **/
.alpaca-container-item
{

}

/** Added to the first container item field within a container **/
.alpaca-container-item-first
{

}

/** Added to the last container item field within a container **/
.alpaca-container-item-last
{

}

/** Added to a container to indicate it is empty **/
.alpaca-container-empty
{

}

/** Added to the dom element holding the toolbar for an array **/
.alpaca-array-toolbar
{

}

/** Added to a button in the array toolbar that triggers an action **/
.alpaca-array-toolbar-action
{

}

/** Added to the dom element holding the actionbar for each array item **/
.alpaca-array-actionbar
{

}

/** Added to a button in an array item actionbar that triggers an action **/
.alpaca-array-actionbar-action
{

}

/** Added to every control outer field element **/
.alpaca-control
{

}

/** Added to the optional label accompanying any control **/
.alpaca-control-label
{

}

/** ******************************************************** **/
/**                        STATE LABELS                      **/
/** ******************************************************** **/

/** Added to top-most control when rendering in display mode **/
.alpaca-display
{

}

/** Added to top-most control when rendering in create mode **/
.alpaca-create
{

}

/** Added to top-most control when rendering in edit mode **/
.alpaca-edit
{

}

/** Added to any field that is optional **/
.alpaca-required
{

}

/** Added to any field that is required **/
.alpaca-optional
{

}

/** Added to any field that is readonly **/
.alpaca-readonly
{

}

/** Added to any field that is disabled **/
.alpaca-disabled
{

}

/** Added to the container that holds Alpaca field helper text **/
.alpaca-helper
{

}

/** Added to form containers that are rendering in horizontal mode **/
.alpaca-horizontal
{

}

/** Added to form containers that are rendering in vertical mode **/
.alpaca-vertical
{

}

/** Added to the top most container element **/
.alpaca-top
{

}

/** Added to fields that are valid **/
.alpaca-valid
{

}

/** Added to fields that have run through validation and are invalid **/
.alpaca-invalid
{

}

/** Added to fields that have run through validation and are invalid but are currently hiding invalidation errors **/
.alpaca-invalid-hidden
{

}

/* Added to additional DOM elements to mark validation messages */
.alpaca-message
{

}

/** Added to messages that are for invalidation states that are current hidden (hideInitValidationError) **/
.alpaca-message-hidden
{

}

/** Added to buttons that are marked disabled */
.alpaca-button-disabled
{

}

/** ******************************************************** **/
/**                           ICONS                          **/
/** ******************************************************** **/

.alpaca-icon-helper
{

}

.alpaca-icon-required
{

}

/** Added to indicate hover state **/
.alpaca-hover
{
}

/** General purpose HTML clear **/
.alpaca-clear
{
    clear: both;
}

.alpaca-float-right
{
    float: right;
}

/** ************************************** **/
/** TWITTER TYPEAHEAD                      **/
/** ************************************** **/

.twitter-typeahead .tt-dropdown-menu
{
    background-color: white;
    border: 1px #ccc solid;
    padding: 10px;
    color: #999;
    width: 100%;
    padding-bottom: 0px;
}

.twitter-typeahead .tt-dropdown-menu P
{
    font-size: 1em;
}

.tt-suggestion.tt-is-under-cursor
{
    background-color: #ccc;
    color: #333;
}

.tt-dropdown-menu
{
    background-color: white;
    border: 1px solid rgb(204, 204, 204);
    width: 100%;
}

/** ************************************** **/
/** EDITOR FIELD                           **/
/** ************************************** **/

.alpaca-controlfield-editor
{
    position: relative;
    width: 100%;
    height: 300px;
    border: 1px #ccc solid;
}

.alpaca-controlfield-editor .control-field-editor-el
{
    position:absolute;
    top:0;
    bottom:0;
    left: 0;
    right:0
}

/** ************************************** **/
/** DATEPICKER (jQueryUI)                  **/
/** ************************************** **/

#ui-datepicker-div
{
    display: none;
    background-color:white;
    z-index: 9999999 !important;
    width: 22em !important;
}

/* Fix for Chrome issue with Button text */
.ui-button .ui-button-text {
    white-space: nowrap;
}

.ui-datepicker
{
    z-index: 100;
}

/** ************************************** **/
/** FILE UPLOAD (jQueryUI)                 **/
/** ************************************** **/

.alpaca-fileupload-container
{
    border: 1px #ccc solid;
    padding: 10px;
    border-radius: 5px;
}

.alpaca-fileupload-container .row
{
    margin-bottom: 10px;
}

.alpaca-fileupload-well
{
    /*border: 1px #ccc solid;*/
    padding: 10px;
    border-radius: 5px;
    min-height: 100px;
}

.alpaca-fileupload-container table
{
    border: 1px #ccc solid;
    padding: 10px;
    border-radius: 5px;
}

.alpaca-fileupload-well p
{
    padding-top: 20px;
    color: #888;
}

.alpaca-fileupload-well table tbody.files tr td.name
{
    word-wrap: break-word;
}

/** ************************************** **/
/** ACE EDITOR                             **/
/** ************************************** **/

.ace_editor
{
    border: 1px solid rgb(204, 204, 204);
}

.has-error .multiselect
{
    border-color: #a94442;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
}

.alpaca-field-tablerow label.control-label
{
    display: none;
}

.alpaca-field-table .actionbar
{
    white-space: nowrap;
    text-align: center;
}

.alpaca-field-table table tr td .alpaca-field
{
    width: 100%;
}

.alpaca-field-table table tr td .alpaca-field .form-control
{
    width: 100%;
}

.alpaca-field-table .form-group
{
    margin-bottom: 0px;
}

.alpaca-field-table .form-group.alpaca-field-checkbox
{
    text-align: center;
}

.alpaca-field-table .alpaca-control.checkbox
{
    /*
    margin: 0px;
    padding: 0px;
    */
    padding-top: 6px;
}

/*
.alpaca-field-table .alpaca-control.checkbox input[type='checkbox']
{
    margin-left: -16px;
    margin-top: -3px;
}
*/

.alpaca-field-table table tr td.actionbar .alpaca-array-actionbar
{
    padding-bottom: 0px;
}

.alpaca-field-table .actionbar .alpaca-array-actionbar.btn-group
{
    width: auto;
}


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

namespace RoslynMapper.Map
{
    public static class Extensions
    {
        public static Type GetMemberType(this MemberInfo member)
        {
            if (member is FieldInfo)
            {
                return (member as FieldInfo).FieldType;
            }
            else if (member is PropertyInfo)
            {
                return (member as PropertyInfo).PropertyType;
            }
            else if (member is MethodInfo)
            {
                return (member as MethodInfo).ReturnType;
            }

            return null;
        }

        public static string GetMemberFullPathName(this IMember member)
        {
            if (string.IsNullOrEmpty(member.Path.AccessPath))
            {
                if (member.MemberInfo is MethodInfo)
                {
                    return member.MemberInfo.Name + "()";
                }
                else
                {
                    return member.MemberInfo.Name;
                }
            }
            else
            {
                if (member.MemberInfo is MethodInfo)
                {
                    return member.Path.AccessPath + "." + member.MemberInfo.Name + "()";
                }
                else
                {
                    return member.Path.AccessPath + "." + member.MemberInfo.Name;
                }
            }
        }

        public static bool IsConcreteType(this Type type)
        {
            return !type.IsAbstract && !type.IsInterface;
        }

        public static bool IsGenericTypeOf(this Type type, Type genericType)
        {
            return ((type.IsGenericType) && type.GetGenericTypeDefinition() == genericType);
        }
    }
}


text:
package com.google.cloud.bigtable.hbase.async;

import static com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule.COLUMN_FAMILY;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import com.google.cloud.bigtable.hbase.AbstractTestSnapshot;
import com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.AsyncAdmin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.SnapshotDescription;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TestAsyncSnapshots extends AbstractTestSnapshot {

  @Before
  public void setUp() throws ExecutionException, InterruptedException, IOException {
    values = createAndPopulateTable(tableName);
  }

  private AsyncAdmin getAsyncAdmin() throws InterruptedException, ExecutionException {
    return AbstractAsyncTest.getAsyncConnection().getAdmin();
  }

  @Test
  public void testListSnapshotsWithNullAndEmptyString() throws IOException {
    Exception actualError = null;
    try {
      listSnapshotsSize((String) null);
    } catch (Exception ex) {
      actualError = ex;
    }
    assertNotNull(actualError);
    assertTrue(actualError instanceof NullPointerException);
    actualError = null;

    try {
      listSnapshotsSize((Pattern) null);
    } catch (Exception ex) {
      actualError = ex;
    }
    assertNotNull(actualError);
    assertTrue(actualError instanceof NullPointerException);

    assertEquals(0, listSnapshotsSize(""));
  }

  @Test
  public void listSnapshots() throws IOException, InterruptedException, ExecutionException {
    String snapshot1 = newSnapshotId();
    snapshot(snapshot1, tableName);

    String snapshot2 = newSnapshotId();
    snapshot(snapshot2, tableName);
    try {
      List<SnapshotDescription> snapshotDescriptions = getAsyncAdmin().listSnapshots().get();
      List<String> descStrings = new ArrayList<>();
      for (SnapshotDescription snapshotDescription : snapshotDescriptions) {
        descStrings.add(snapshotDescription.getName());
      }
      assertThat(descStrings, hasItems(snapshot1, snapshot2));
    } finally {
      deleteSnapshot(snapshot1);
      deleteSnapshot(snapshot2);
    }
  }

  private TableDescriptor createDescriptor(TableName tableName) {
    return TableDescriptorBuilder.newBuilder(tableName)
        .addColumnFamily(
            ColumnFamilyDescriptorBuilder.newBuilder(SharedTestEnvRule.COLUMN_FAMILY).build())
        .build();
  }

  @Override
  protected void snapshot(String snapshotName, TableName tableName) throws IOException {
    try {
      getAsyncAdmin().snapshot(snapshotName, tableName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while creating snapshot: " + e.getCause());
    }
  }

  protected Map<String, Long> createAndPopulateTable(TableName tableName) throws IOException {
    try {
      getAsyncAdmin().createTable(createDescriptor(tableName)).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while creating table: " + e.getCause());
    }

    Map<String, Long> values = new HashMap<>();
    try (Table table = getConnection().getTable(tableName)) {
      List<Put> puts = new ArrayList<>();
      for (long i = 0; i < 10; i++) {
        final UUID rowKey = UUID.randomUUID();
        byte[] row = Bytes.toBytes(rowKey.toString());
        values.put(rowKey.toString(), i);
        puts.add(new Put(row).addColumn(COLUMN_FAMILY, QUALIFIER, Bytes.toBytes(i)));
      }
      table.put(puts);
    }
    return values;
  }

  @Override
  protected void deleteSnapshot(String snapshotName) throws IOException {
    try {
      getAsyncAdmin().deleteSnapshot(snapshotName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while deleting snapshot: " + e.getCause());
    }
  }

  @Override
  protected boolean tableExists(TableName tableName) throws IOException {
    try {
      return getAsyncAdmin().tableExists(tableName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while checking table exists: " + e.getCause());
    }
  }

  @Override
  protected void disableTable(TableName tableName) throws IOException {
    try {
      getAsyncAdmin().disableTable(tableName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while disabling table: " + e.getCause());
    }
  }

  @Override
  protected void cloneSnapshot(String snapshotName, TableName tableName)
      throws IOException, TableExistsException, RestoreSnapshotException {
    try {
      getAsyncAdmin().cloneSnapshot(snapshotName, tableName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while creating clone of snapshot: " + e.getCause());
    }
  }

  @Override
  protected int listSnapshotsSize(String regEx) throws IOException {
    try {
      Pattern pattern = Pattern.compile(regEx);
      return getAsyncAdmin().listSnapshots(pattern).get().size();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while listing snapshots size: " + e.getCause());
    }
  }

  @Override
  protected int listSnapshotsSize(Pattern pattern) throws IOException {
    try {
      return getAsyncAdmin().listSnapshots(pattern).get().size();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while listing snapshots size: " + e.getCause());
    }
  }

  @Override
  protected void deleteTable(TableName tableName) throws IOException {
    try {
      getAsyncAdmin().deleteTable(tableName).get();
    } catch (InterruptedException | ExecutionException e) {
      throw new IOException("Error while deleting table: " + e.getCause());
    }
  }
}


text:
from datetime import datetime

from django.conf import settings
from django.db import models
from django.utils import timezone

import jsonfield

from .signals import event_logged

class Log(models.Model):

    user = models.ForeignKey(
        getattr(settings, "AUTH_USER_MODEL", "auth.User"),
        null=True,
        on_delete=models.SET_NULL
    )
    timestamp = models.DateTimeField(default=timezone.now, db_index=True)
    action = models.CharField(max_length=50, db_index=True)
    extra = jsonfield.JSONField()

    class Meta:
        ordering = ["-timestamp"]

def log(user, action, extra=None):
    if (user is not None and not user.is_authenticated()):
        user = None
    if extra is None:
        extra = {}
    event = Log.objects.create(user=user, action=action, extra=extra)
    event_logged.send(sender=Log, event=event)
    return event


text:
//-----------------------------------------------------------------------
// <copyright file="DocumentViewHost.cs" company="Development In Progress Ltd">
//     Copyright © 2012. All rights reserved.
// </copyright>
// <author>Grant Colley</author>
//-----------------------------------------------------------------------

using DevelopmentInProgress.Origin.RegionAdapters;
using System.Windows.Controls;

namespace DevelopmentInProgress.Origin.View
{
    /// <summary>
    /// The host for the document view set as the content for the
    /// regions host control in <see cref="DockingManagerBehavior"/>.
    /// The <see cref="DocumentViewHost"/> provides common functionality
    /// such as navigation history, refresh and messaging.
    /// </summary>
    public partial class DocumentViewHost : UserControl
    {
        public DocumentViewHost(DocumentViewBase documentViewBase)
        {
            InitializeComponent();

            MainContent.Content = documentViewBase;
            DataContext = documentViewBase.DataContext;
            ModuleName = documentViewBase.ModuleName;
        }

        /// <summary>
        /// Gets or sets the module name.
        /// </summary>
        public string ModuleName { get; private set; }

        /// <summary>
        /// Gets an instance of the <see cref="DocumentViewBase"/>.
        /// </summary>
        public DocumentViewBase View
        {
            get { return MainContent.Content as DocumentViewBase; }
        }
    }
}


text:
import {assert} from 'chai';
import promiseRetry from '../src/index';

describe('promise-retry-or-throw', function () {
    it('Immediately resolves if action is successful', function () {
        const action = () => Promise.resolve();
        return promiseRetry(action);
    });

    it('Can succeed after a few attempts', function () {
        this.timeout(0);
        const options = {
            maxNumberOfRetries: 4,
            delayIncrease: 1
        }

        let attempt = 0;
        return promiseRetry(makeThreeAttempts, options)
            .then(() => assert.equal(attempt, 3));

        function makeThreeAttempts() {
            attempt++;
            return attempt == 3 ? Promise.resolve() : Promise.reject();
        }
    });

    it('Actions on some data are returned correctly', function () {
        const data = [0, 1, 2];
        const action = () => Promise.resolve(data);
        return promiseRetry(action)
            .then(response => assert.deepEqual(response, data));
    });

    it('Can throw early if given an error filter function', function () {
        const action = () => Promise.reject('test');
        const options = {
            filter: (error) => error == 'test'
        }

        return promiseRetry(action, options)
            .then(() => {
                throw new Error('promiseRetry should not have resolved')
            })
            .catch(error => assert.equal(error, 'test'));
    });

    describe('time delay calculation', function () {
        it("default delay function should increase linearly on each retry attempt", function () {
            const options = {
                maxNumberOfRetries: 40,
                delayIncrease: 10
            };

            let start = Date.now();
            let delay = 0;
            let attempts = 0;
            const action = () => {
                attempts++;
                const now = Date.now();
                assert.equal(now >= start + delay, true);
                delay += options.delayIncrease;
                start = now;
                return attempts > 5 ? Promise.resolve() : Promise.reject();
            };

            return promiseRetry(action, options);
        });

        it("a user defined delay strategy can be used", function () {
            const doubleDelayIncrease = ({delay, delayIncrease}) => {
                return delay + (delayIncrease * 2);
            }

            const options = {
                maxNumberOfRetries: 40,
                delayIncrease: 10,
                calculateDelay: doubleDelayIncrease
            };

            let start = Date.now();
            let delay = 0;
            let attempts = 0;
            const action = () => {
                attempts++;
                const now = Date.now();
                assert.equal(now >= start + delay, true);
                delay += (options.delayIncrease * 2);
                start = now;
                return attempts > 5 ? Promise.resolve() : Promise.reject();
            };

            return promiseRetry(action, options);
        });

    });
});


text:
package org.eclipse.dd.dc.impl;

import com.google.gwt.user.client.rpc.GwtTransient;

import java.util.Map;

import org.eclipse.dd.dc.DcPackage;
import org.eclipse.dd.dc.Font;

import org.eclipse.dd.dc.util.DcValidator;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;

import org.eclipse.emf.ecore.plugin.EcorePlugin;

import org.eclipse.emf.ecore.util.EObjectValidator;

/**
 *
 * An implementation of the model object 'Font'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link org.eclipse.dd.dc.impl.FontImpl#isIsBold Is Bold}

 *
{@link org.eclipse.dd.dc.impl.FontImpl#isIsItalic Is Italic}

 *
{@link org.eclipse.dd.dc.impl.FontImpl#isIsStrikeThrough Is Strike Through}

 *
{@link org.eclipse.dd.dc.impl.FontImpl#isIsUnderline Is Underline}

 *
{@link org.eclipse.dd.dc.impl.FontImpl#getName Name}

 *
{@link org.eclipse.dd.dc.impl.FontImpl#getSize Size}

 *

 *
 * @generated
 */
public class FontImpl extends EObjectImpl implements Font {
	/**
	 * The default value of the '{@link #isIsBold() Is Bold}' attribute.
	 *
	 *
	 * @see #isIsBold()
	 * @generated
	 * @ordered
	 */
	protected static final boolean IS_BOLD_EDEFAULT = false;

	/**
	 * The cached value of the '{@link #isIsBold() Is Bold}' attribute.
	 *
	 *
	 * @see #isIsBold()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected boolean isBold = IS_BOLD_EDEFAULT;

	/**
	 * The default value of the '{@link #isIsItalic() Is Italic}' attribute.
	 *
	 *
	 * @see #isIsItalic()
	 * @generated
	 * @ordered
	 */
	protected static final boolean IS_ITALIC_EDEFAULT = false;

	/**
	 * The cached value of the '{@link #isIsItalic() Is Italic}' attribute.
	 *
	 *
	 * @see #isIsItalic()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected boolean isItalic = IS_ITALIC_EDEFAULT;

	/**
	 * The default value of the '{@link #isIsStrikeThrough() Is Strike Through}' attribute.
	 *
	 *
	 * @see #isIsStrikeThrough()
	 * @generated
	 * @ordered
	 */
	protected static final boolean IS_STRIKE_THROUGH_EDEFAULT = false;

	/**
	 * The cached value of the '{@link #isIsStrikeThrough() Is Strike Through}' attribute.
	 *
	 *
	 * @see #isIsStrikeThrough()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected boolean isStrikeThrough = IS_STRIKE_THROUGH_EDEFAULT;

	/**
	 * The default value of the '{@link #isIsUnderline() Is Underline}' attribute.
	 *
	 *
	 * @see #isIsUnderline()
	 * @generated
	 * @ordered
	 */
	protected static final boolean IS_UNDERLINE_EDEFAULT = false;

	/**
	 * The cached value of the '{@link #isIsUnderline() Is Underline}' attribute.
	 *
	 *
	 * @see #isIsUnderline()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected boolean isUnderline = IS_UNDERLINE_EDEFAULT;

	/**
	 * The default value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected static final String NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected String name = NAME_EDEFAULT;

	/**
	 * The default value of the '{@link #getSize() Size}' attribute.
	 *
	 *
	 * @see #getSize()
	 * @generated
	 * @ordered
	 */
	protected static final float SIZE_EDEFAULT = 0.0F;

	/**
	 * The cached value of the '{@link #getSize() Size}' attribute.
	 *
	 *
	 * @see #getSize()
	 * @generated
	 * @ordered
	 */
	@GwtTransient
	protected float size = SIZE_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected FontImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return DcPackage.Literals.FONT;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean isIsBold() {
		return isBold;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setIsBold(boolean newIsBold) {
		boolean oldIsBold = isBold;
		isBold = newIsBold;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__IS_BOLD, oldIsBold, isBold));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean isIsItalic() {
		return isItalic;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setIsItalic(boolean newIsItalic) {
		boolean oldIsItalic = isItalic;
		isItalic = newIsItalic;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__IS_ITALIC, oldIsItalic, isItalic));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean isIsStrikeThrough() {
		return isStrikeThrough;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setIsStrikeThrough(boolean newIsStrikeThrough) {
		boolean oldIsStrikeThrough = isStrikeThrough;
		isStrikeThrough = newIsStrikeThrough;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__IS_STRIKE_THROUGH, oldIsStrikeThrough,
					isStrikeThrough));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean isIsUnderline() {
		return isUnderline;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setIsUnderline(boolean newIsUnderline) {
		boolean oldIsUnderline = isUnderline;
		isUnderline = newIsUnderline;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__IS_UNDERLINE, oldIsUnderline,
					isUnderline));
	}

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

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setName(String newName) {
		String oldName = name;
		name = newName;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__NAME, oldName, name));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public float getSize() {
		return size;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void setSize(float newSize) {
		float oldSize = size;
		size = newSize;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DcPackage.FONT__SIZE, oldSize, size));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean non_negative_size(DiagnosticChain diagnostics, Map<Object, Object> context) {
		// TODO: implement this method
		// -> specify the condition that violates the invariant
		// -> verify the details of the diagnostic, including severity and message
		// Ensure that you remove @generated or mark it @generated NOT
		if (false) {
			if (diagnostics != null) {
				diagnostics.add(new BasicDiagnostic(Diagnostic.ERROR, DcValidator.DIAGNOSTIC_SOURCE,
						DcValidator.FONT__NON_NEGATIVE_SIZE,
						EcorePlugin.INSTANCE.getString("_UI_GenericInvariant_diagnostic",
								new Object[] { "non_negative_size", EObjectValidator.getObjectLabel(this, context) }),
						new Object[] { this }));
			}
			return false;
		}
		return true;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
		case DcPackage.FONT__IS_BOLD:
			return isIsBold();
		case DcPackage.FONT__IS_ITALIC:
			return isIsItalic();
		case DcPackage.FONT__IS_STRIKE_THROUGH:
			return isIsStrikeThrough();
		case DcPackage.FONT__IS_UNDERLINE:
			return isIsUnderline();
		case DcPackage.FONT__NAME:
			return getName();
		case DcPackage.FONT__SIZE:
			return getSize();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
		case DcPackage.FONT__IS_BOLD:
			setIsBold((Boolean) newValue);
			return;
		case DcPackage.FONT__IS_ITALIC:
			setIsItalic((Boolean) newValue);
			return;
		case DcPackage.FONT__IS_STRIKE_THROUGH:
			setIsStrikeThrough((Boolean) newValue);
			return;
		case DcPackage.FONT__IS_UNDERLINE:
			setIsUnderline((Boolean) newValue);
			return;
		case DcPackage.FONT__NAME:
			setName((String) newValue);
			return;
		case DcPackage.FONT__SIZE:
			setSize((Float) newValue);
			return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
		case DcPackage.FONT__IS_BOLD:
			setIsBold(IS_BOLD_EDEFAULT);
			return;
		case DcPackage.FONT__IS_ITALIC:
			setIsItalic(IS_ITALIC_EDEFAULT);
			return;
		case DcPackage.FONT__IS_STRIKE_THROUGH:
			setIsStrikeThrough(IS_STRIKE_THROUGH_EDEFAULT);
			return;
		case DcPackage.FONT__IS_UNDERLINE:
			setIsUnderline(IS_UNDERLINE_EDEFAULT);
			return;
		case DcPackage.FONT__NAME:
			setName(NAME_EDEFAULT);
			return;
		case DcPackage.FONT__SIZE:
			setSize(SIZE_EDEFAULT);
			return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
		case DcPackage.FONT__IS_BOLD:
			return isBold != IS_BOLD_EDEFAULT;
		case DcPackage.FONT__IS_ITALIC:
			return isItalic != IS_ITALIC_EDEFAULT;
		case DcPackage.FONT__IS_STRIKE_THROUGH:
			return isStrikeThrough != IS_STRIKE_THROUGH_EDEFAULT;
		case DcPackage.FONT__IS_UNDERLINE:
			return isUnderline != IS_UNDERLINE_EDEFAULT;
		case DcPackage.FONT__NAME:
			return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
		case DcPackage.FONT__SIZE:
			return size != SIZE_EDEFAULT;
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy())
			return super.toString();

		StringBuilder result = new StringBuilder(super.toString());
		result.append(" (isBold: ");
		result.append(isBold);
		result.append(", isItalic: ");
		result.append(isItalic);
		result.append(", isStrikeThrough: ");
		result.append(isStrikeThrough);
		result.append(", isUnderline: ");
		result.append(isUnderline);
		result.append(", name: ");
		result.append(name);
		result.append(", size: ");
		result.append(size);
		result.append(')');
		return result.toString();
	}

} //FontImpl


text:
layout: post
title: Closer
date: 2016-03-21 16:16:57.000000000 +02:00
permalink: /2016/03/21/closer/
featured:
  path: /assets/uploads/closer_1.jpg
  alt: Closer
images:
- path: /assets/uploads/closer_1.jpg
  alt: Closer
type: post
published: true
status: publish
categories:
- Nudes
---


text:
package com.fsck.zywxMailk9.mail.store.imap;

import android.util.Log;

import com.fsck.zywxMailk9.K9;

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

/**
 * Utility methods for use with IMAP.
 */
public class ImapUtility {
    /**
     * Gets all of the values in a sequence set per RFC 3501.
     *
     *

     * Any ranges are expanded into a list of individual numbers.
     *

     *
     *

     * sequence-number = nz-number / "*"
     * sequence-range  = sequence-number ":" sequence-number
     * sequence-set    = (sequence-number / sequence-range) *("," sequence-set)
     *

     *
     * @param set
     *         The sequence set string as received by the server.
     *
     * @return The list of IDs as strings in this sequence set. If the set is invalid, an empty
     *         list is returned.
     */
    public static List<String> getImapSequenceValues(String set) {
        ArrayList<String> list = new ArrayList<String>();
        if (set != null) {
            String[] setItems = set.split(",");
            for (String item : setItems) {
                if (item.indexOf(':') == -1) {
                    // simple item
                    try {
                        Integer.parseInt(item); // Don't need the value; just ensure it's valid
                        list.add(item);
                    } catch (NumberFormatException e) {
                        Log.d(K9.LOG_TAG, "Invalid UID value", e);
                    }
                } else {
                    // range
                    list.addAll(getImapRangeValues(item));
                }
            }
        }

        return list;
    }

    /**
     * Expand the given number range into a list of individual numbers.
     *
     *

     * sequence-number = nz-number / "*"
     * sequence-range  = sequence-number ":" sequence-number
     * sequence-set    = (sequence-number / sequence-range) *("," sequence-set)
     *

     *
     * @param range
     *         The range string as received by the server.
     *
     * @return The list of IDs as strings in this range. If the range is not valid, an empty list
     *         is returned.
     */
    public static List<String> getImapRangeValues(String range) {
        ArrayList<String> list = new ArrayList<String>();
        try {
            if (range != null) {
                int colonPos = range.indexOf(':');
                if (colonPos > 0) {
                    int first  = Integer.parseInt(range.substring(0, colonPos));
                    int second = Integer.parseInt(range.substring(colonPos + 1));
                    if (first < second) {
                        for (int i = first; i <= second; i++) {
                            list.add(Integer.toString(i));
                        }
                    } else {
                        for (int i = first; i >= second; i--) {
                            list.add(Integer.toString(i));
                        }
                    }
                }
            }
        } catch (NumberFormatException e) {
            Log.d(K9.LOG_TAG, "Invalid range value", e);
        }

        return list;
    }
}


text:
package org.microbule.test.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit;
import org.junit.After;
import org.junit.Before;
import org.microbule.api.JaxrsConfigService;
import org.microbule.api.JaxrsServer;
import org.microbule.config.api.Config;
import org.microbule.config.core.MapConfig;
import org.microbule.container.core.SimpleContainer;
import org.microbule.core.DefaultJaxrsProxyFactory;
import org.microbule.core.DefaultJaxrsServerFactory;
import org.microbule.core.DefaultJaxrsServiceDiscovery;
import org.microbule.scheduler.core.DefaultSchedulerService;
import org.microbule.test.core.MockObjectTestCase;
import org.microbule.util.reflect.Types;

public abstract class JaxrsServerTestCase<T> extends MockObjectTestCase implements JaxrsConfigService {
//----------------------------------------------------------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------------------------------------------------------

    private static final String BASE_ADDRESS_PATTERN = "http://localhost:%d/%s";

    private JaxrsServer server;
    private String baseAddress;
    private final SimpleContainer container = new SimpleContainer();
    private DefaultJaxrsProxyFactory proxyFactory;

//----------------------------------------------------------------------------------------------------------------------
// Abstract Methods
//----------------------------------------------------------------------------------------------------------------------

    protected abstract T createImplementation();

//----------------------------------------------------------------------------------------------------------------------
// JaxrsConfigService Implementation
//----------------------------------------------------------------------------------------------------------------------

    @Override
    public Config createConfig(String... path) {
        MapConfig config = new MapConfig();
        configureGlobalConfig(config);
        return config;
    }

    @Override
    public final <I> Config createProxyConfig(Class<I> serviceInterface, String serviceName) {
        MapConfig config = new MapConfig();
        configureProxy(config);
        config.addValue(DefaultJaxrsServiceDiscovery.PROXY_ADDRESS_PROP, baseAddress);
        return config;
    }

    @Override
    public final <I> Config createServerConfig(Class<I> serviceInterface, String serviceName) {
        MapConfig config = new MapConfig();
        configureServer(config);
        config.addValue(DefaultJaxrsServerFactory.SERVER_ADDRESS_PROP, baseAddress);
        return config;
    }

//----------------------------------------------------------------------------------------------------------------------
// Getter/Setter Methods
//----------------------------------------------------------------------------------------------------------------------

    public String getBaseAddress() {
        return baseAddress;
    }

//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------

    protected void addBeans(SimpleContainer container) {
        // Do nothing!
    }

    protected int calculatePort() {
        try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLocalHost())) {
            return socket.getLocalPort();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to allocate port for test case.", e);
        }
    }

    protected void configureGlobalConfig(MapConfig globalConfig) {
        // Do nothing!
    }

    protected void configureProxy(MapConfig proxyConfig) {
        // Do nothing!
    }

    protected void configureServer(MapConfig serverConfig) {
        // Do nothing!
    }

    protected String createBaseAddress() {
        return String.format(BASE_ADDRESS_PATTERN, calculatePort(), getClass().getSimpleName());
    }

    protected T createProxy() {
        return proxyFactory.createProxy(getServiceInterface());
    }

    private Class<T> getServiceInterface() {
        return Types.getTypeParameter(getClass(), JaxrsServerTestCase.class, 0);
    }

    protected WebTarget createWebTarget() {
        return ClientBuilder.newClient().target(getBaseAddress()).property(AsyncHTTPConduit.USE_ASYNC, Boolean.TRUE);
    }

    @After
    public void shutdownServer() {
        if (server != null) {
            server.shutdown();
        }
    }

    @Before
    public void startServer() {
        addBeans(container);
        final DefaultJaxrsServerFactory factory = new DefaultJaxrsServerFactory(container, this);
        proxyFactory = new DefaultJaxrsProxyFactory(container, this, new DefaultSchedulerService(1));
        container.initialize();

        baseAddress = createBaseAddress();
        server = factory.createJaxrsServer(getServiceInterface(), createImplementation());
    }
}


text:
class ApplicationController < ActionController::Base
  include Pundit

  after_action :verify_authorized, except: :index, unless: :skipped_controller?
  after_action :verify_policy_scoped, only: :index, unless: :skipped_controller?

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def new_session_path(_scope)
    root_path
  end

  def pundit_user
    current_organizer
  end

  def skipped_controller?
    devise_controller? || self.is_a?(RailsAdmin::ApplicationController)
  end
end


text:
package com.github.mottox.taomp.concurrent.locks;

import org.junit.Test;

/**
 * {@link TTASLock}测试类。
 *
 * @author Robin Wang
 */
public class TTASLockTest {

    @Test(timeout = 10000)
    public void testLockAndUnlock() throws Exception {
        LockTestHelper.testLockAndUnlock(new TTASLock());
    }
}


text:
(() => {
	// Map multiple JavaScript environments to a single common API,
	// preferring web standards over Node.js API.
	//
	// Environments considered:
	// - Browsers
	// - Node.js
	// - Electron
	// - Parcel

	if (typeof global !== "undefined") {
		// global already exists
	} else if (typeof window !== "undefined") {
		window.global = window;
	} else if (typeof self !== "undefined") {
		self.global = self;
	} else {
		throw new Error("cannot export Go (neither global, window nor self is defined)");
	}

	if (!global.require && typeof require !== "undefined") {
		global.require = require;
	}

	if (!global.fs && global.require) {
		global.fs = require("fs");
	}

	const enosys = () => {
		const err = new Error("not implemented");
		err.code = "ENOSYS";
		return err;
	};

	if (!global.fs) {
		let outputBuf = "";
		global.fs = {
			constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
			writeSync(fd, buf) {
				outputBuf += decoder.decode(buf);
				const nl = outputBuf.lastIndexOf("\n");
				if (nl != -1) {
					console.log(outputBuf.substr(0, nl));
					outputBuf = outputBuf.substr(nl + 1);
				}
				return buf.length;
			},
			write(fd, buf, offset, length, position, callback) {
				if (offset !== 0 || length !== buf.length || position !== null) {
					callback(enosys());
					return;
				}
				const n = this.writeSync(fd, buf);
				callback(null, n);
			},
			chmod(path, mode, callback) { callback(enosys()); },
			chown(path, uid, gid, callback) { callback(enosys()); },
			close(fd, callback) { callback(enosys()); },
			fchmod(fd, mode, callback) { callback(enosys()); },
			fchown(fd, uid, gid, callback) { callback(enosys()); },
			fstat(fd, callback) { callback(enosys()); },
			fsync(fd, callback) { callback(null); },
			ftruncate(fd, length, callback) { callback(enosys()); },
			lchown(path, uid, gid, callback) { callback(enosys()); },
			link(path, link, callback) { callback(enosys()); },
			lstat(path, callback) { callback(enosys()); },
			mkdir(path, perm, callback) { callback(enosys()); },
			open(path, flags, mode, callback) { callback(enosys()); },
			read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
			readdir(path, callback) { callback(enosys()); },
			readlink(path, callback) { callback(enosys()); },
			rename(from, to, callback) { callback(enosys()); },
			rmdir(path, callback) { callback(enosys()); },
			stat(path, callback) { callback(enosys()); },
			symlink(path, link, callback) { callback(enosys()); },
			truncate(path, length, callback) { callback(enosys()); },
			unlink(path, callback) { callback(enosys()); },
			utimes(path, atime, mtime, callback) { callback(enosys()); },
		};
	}

	if (!global.process) {
		global.process = {
			getuid() { return -1; },
			getgid() { return -1; },
			geteuid() { return -1; },
			getegid() { return -1; },
			getgroups() { throw enosys(); },
			pid: -1,
			ppid: -1,
			umask() { throw enosys(); },
			cwd() { throw enosys(); },
			chdir() { throw enosys(); },
		}
	}

	if (!global.crypto) {
		const nodeCrypto = require("crypto");
		global.crypto = {
			getRandomValues(b) {
				nodeCrypto.randomFillSync(b);
			},
		};
	}

	if (!global.performance) {
		global.performance = {
			now() {
				const [sec, nsec] = process.hrtime();
				return sec * 1000 + nsec / 1000000;
			},
		};
	}

	if (!global.TextEncoder) {
		global.TextEncoder = require("util").TextEncoder;
	}

	if (!global.TextDecoder) {
		global.TextDecoder = require("util").TextDecoder;
	}

	// End of polyfills for common API.

	const encoder = new TextEncoder("utf-8");
	const decoder = new TextDecoder("utf-8");

	global.Go = class {
		constructor() {
			this.argv = ["js"];
			this.env = {};
			this.exit = (code) => {
				if (code !== 0) {
					console.warn("exit code:", code);
				}
			};
			this._exitPromise = new Promise((resolve) => {
				this._resolveExitPromise = resolve;
			});
			this._pendingEvent = null;
			this._scheduledTimeouts = new Map();
			this._nextCallbackTimeoutID = 1;

			const setInt64 = (addr, v) => {
				this.mem.setUint32(addr + 0, v, true);
				this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
			}

			const getInt64 = (addr) => {
				const low = this.mem.getUint32(addr + 0, true);
				const high = this.mem.getInt32(addr + 4, true);
				return low + high * 4294967296;
			}

			const loadValue = (addr) => {
				const f = this.mem.getFloat64(addr, true);
				if (f === 0) {
					return undefined;
				}
				if (!isNaN(f)) {
					return f;
				}

				const id = this.mem.getUint32(addr, true);
				return this._values[id];
			}

			const storeValue = (addr, v) => {
				const nanHead = 0x7FF80000;

				if (typeof v === "number") {
					if (isNaN(v)) {
						this.mem.setUint32(addr + 4, nanHead, true);
						this.mem.setUint32(addr, 0, true);
						return;
					}
					if (v === 0) {
						this.mem.setUint32(addr + 4, nanHead, true);
						this.mem.setUint32(addr, 1, true);
						return;
					}
					this.mem.setFloat64(addr, v, true);
					return;
				}

				switch (v) {
					case undefined:
						this.mem.setFloat64(addr, 0, true);
						return;
					case null:
						this.mem.setUint32(addr + 4, nanHead, true);
						this.mem.setUint32(addr, 2, true);
						return;
					case true:
						this.mem.setUint32(addr + 4, nanHead, true);
						this.mem.setUint32(addr, 3, true);
						return;
					case false:
						this.mem.setUint32(addr + 4, nanHead, true);
						this.mem.setUint32(addr, 4, true);
						return;
				}

				let id = this._ids.get(v);
				if (id === undefined) {
					id = this._idPool.pop();
					if (id === undefined) {
						id = this._values.length;
					}
					this._values[id] = v;
					this._goRefCounts[id] = 0;
					this._ids.set(v, id);
				}
				this._goRefCounts[id]++;
				let typeFlag = 1;
				switch (typeof v) {
					case "string":
						typeFlag = 2;
						break;
					case "symbol":
						typeFlag = 3;
						break;
					case "function":
						typeFlag = 4;
						break;
				}
				this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
				this.mem.setUint32(addr, id, true);
			}

			const loadSlice = (addr) => {
				const array = getInt64(addr + 0);
				const len = getInt64(addr + 8);
				return new Uint8Array(this._inst.exports.mem.buffer, array, len);
			}

			const loadSliceOfValues = (addr) => {
				const array = getInt64(addr + 0);
				const len = getInt64(addr + 8);
				const a = new Array(len);
				for (let i = 0; i < len; i++) {
					a[i] = loadValue(array + i * 8);
				}
				return a;
			}

			const loadString = (addr) => {
				const saddr = getInt64(addr + 0);
				const len = getInt64(addr + 8);
				return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
			}

			const timeOrigin = Date.now() - performance.now();
			this.importObject = {
				go: {
					// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
					// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
					// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
					// This changes the SP, thus we have to update the SP used by the imported function.

					// func wasmExit(code int32)
					"runtime.wasmExit": (sp) => {
						const code = this.mem.getInt32(sp + 8, true);
						this.exited = true;
						delete this._inst;
						delete this._values;
						delete this._goRefCounts;
						delete this._ids;
						delete this._idPool;
						this.exit(code);
					},

					// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
					"runtime.wasmWrite": (sp) => {
						const fd = getInt64(sp + 8);
						const p = getInt64(sp + 16);
						const n = this.mem.getInt32(sp + 24, true);
						fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
					},

					// func resetMemoryDataView()
					"runtime.resetMemoryDataView": (sp) => {
						this.mem = new DataView(this._inst.exports.mem.buffer);
					},

					// func nanotime1() int64
					"runtime.nanotime1": (sp) => {
						setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
					},

					// func walltime1() (sec int64, nsec int32)
					"runtime.walltime1": (sp) => {
						const msec = (new Date).getTime();
						setInt64(sp + 8, msec / 1000);
						this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
					},

					// func scheduleTimeoutEvent(delay int64) int32
					"runtime.scheduleTimeoutEvent": (sp) => {
						const id = this._nextCallbackTimeoutID;
						this._nextCallbackTimeoutID++;
						this._scheduledTimeouts.set(id, setTimeout(
							() => {
								this._resume();
								while (this._scheduledTimeouts.has(id)) {
									// for some reason Go failed to register the timeout event, log and try again
									// (temporary workaround for https://github.com/golang/go/issues/28975)
									console.warn("scheduleTimeoutEvent: missed timeout event");
									this._resume();
								}
							},
							getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
						));
						this.mem.setInt32(sp + 16, id, true);
					},

					// func clearTimeoutEvent(id int32)
					"runtime.clearTimeoutEvent": (sp) => {
						const id = this.mem.getInt32(sp + 8, true);
						clearTimeout(this._scheduledTimeouts.get(id));
						this._scheduledTimeouts.delete(id);
					},

					// func getRandomData(r []byte)
					"runtime.getRandomData": (sp) => {
						crypto.getRandomValues(loadSlice(sp + 8));
					},

					// func finalizeRef(v ref)
					"syscall/js.finalizeRef": (sp) => {
						const id = this.mem.getUint32(sp + 8, true);
						this._goRefCounts[id]--;
						if (this._goRefCounts[id] === 0) {
							const v = this._values[id];
							this._values[id] = null;
							this._ids.delete(v);
							this._idPool.push(id);
						}
					},

					// func stringVal(value string) ref
					"syscall/js.stringVal": (sp) => {
						storeValue(sp + 24, loadString(sp + 8));
					},

					// func valueGet(v ref, p string) ref
					"syscall/js.valueGet": (sp) => {
						const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
						sp = this._inst.exports.getsp(); // see comment above
						storeValue(sp + 32, result);
					},

					// func valueSet(v ref, p string, x ref)
					"syscall/js.valueSet": (sp) => {
						Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
					},

					// func valueDelete(v ref, p string)
					"syscall/js.valueDelete": (sp) => {
						Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
					},

					// func valueIndex(v ref, i int) ref
					"syscall/js.valueIndex": (sp) => {
						storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
					},

					// valueSetIndex(v ref, i int, x ref)
					"syscall/js.valueSetIndex": (sp) => {
						Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
					},

					// func valueCall(v ref, m string, args []ref) (ref, bool)
					"syscall/js.valueCall": (sp) => {
						try {
							const v = loadValue(sp + 8);
							const m = Reflect.get(v, loadString(sp + 16));
							const args = loadSliceOfValues(sp + 32);
							const result = Reflect.apply(m, v, args);
							sp = this._inst.exports.getsp(); // see comment above
							storeValue(sp + 56, result);
							this.mem.setUint8(sp + 64, 1);
						} catch (err) {
							storeValue(sp + 56, err);
							this.mem.setUint8(sp + 64, 0);
						}
					},

					// func valueInvoke(v ref, args []ref) (ref, bool)
					"syscall/js.valueInvoke": (sp) => {
						try {
							const v = loadValue(sp + 8);
							const args = loadSliceOfValues(sp + 16);
							const result = Reflect.apply(v, undefined, args);
							sp = this._inst.exports.getsp(); // see comment above
							storeValue(sp + 40, result);
							this.mem.setUint8(sp + 48, 1);
						} catch (err) {
							storeValue(sp + 40, err);
							this.mem.setUint8(sp + 48, 0);
						}
					},

					// func valueNew(v ref, args []ref) (ref, bool)
					"syscall/js.valueNew": (sp) => {
						try {
							const v = loadValue(sp + 8);
							const args = loadSliceOfValues(sp + 16);
							const result = Reflect.construct(v, args);
							sp = this._inst.exports.getsp(); // see comment above
							storeValue(sp + 40, result);
							this.mem.setUint8(sp + 48, 1);
						} catch (err) {
							storeValue(sp + 40, err);
							this.mem.setUint8(sp + 48, 0);
						}
					},

					// func valueLength(v ref) int
					"syscall/js.valueLength": (sp) => {
						setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
					},

					// valuePrepareString(v ref) (ref, int)
					"syscall/js.valuePrepareString": (sp) => {
						const str = encoder.encode(String(loadValue(sp + 8)));
						storeValue(sp + 16, str);
						setInt64(sp + 24, str.length);
					},

					// valueLoadString(v ref, b []byte)
					"syscall/js.valueLoadString": (sp) => {
						const str = loadValue(sp + 8);
						loadSlice(sp + 16).set(str);
					},

					// func valueInstanceOf(v ref, t ref) bool
					"syscall/js.valueInstanceOf": (sp) => {
						this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16));
					},

					// func copyBytesToGo(dst []byte, src ref) (int, bool)
					"syscall/js.copyBytesToGo": (sp) => {
						const dst = loadSlice(sp + 8);
						const src = loadValue(sp + 32);
						if (!(src instanceof Uint8Array)) {
							this.mem.setUint8(sp + 48, 0);
							return;
						}
						const toCopy = src.subarray(0, dst.length);
						dst.set(toCopy);
						setInt64(sp + 40, toCopy.length);
						this.mem.setUint8(sp + 48, 1);
					},

					// func copyBytesToJS(dst ref, src []byte) (int, bool)
					"syscall/js.copyBytesToJS": (sp) => {
						const dst = loadValue(sp + 8);
						const src = loadSlice(sp + 16);
						if (!(dst instanceof Uint8Array)) {
							this.mem.setUint8(sp + 48, 0);
							return;
						}
						const toCopy = src.subarray(0, dst.length);
						dst.set(toCopy);
						setInt64(sp + 40, toCopy.length);
						this.mem.setUint8(sp + 48, 1);
					},

					"debug": (value) => {
						console.log(value);
					},
				}
			};
		}

		async run(instance) {
			this._inst = instance;
			this.mem = new DataView(this._inst.exports.mem.buffer);
			this._values = [ // JS values that Go currently has references to, indexed by reference id
				NaN,
				0,
				null,
				true,
				false,
				global,
				this,
			];
			this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id
			this._ids = new Map();  // mapping from JS values to reference ids
			this._idPool = [];      // unused ids that have been garbage collected
			this.exited = false;    // whether the Go program has exited

			// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
			let offset = 4096;

			const strPtr = (str) => {
				const ptr = offset;
				const bytes = encoder.encode(str + "\0");
				new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
				offset += bytes.length;
				if (offset % 8 !== 0) {
					offset += 8 - (offset % 8);
				}
				return ptr;
			};

			const argc = this.argv.length;

			const argvPtrs = [];
			this.argv.forEach((arg) => {
				argvPtrs.push(strPtr(arg));
			});
			argvPtrs.push(0);

			const keys = Object.keys(this.env).sort();
			keys.forEach((key) => {
				argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
			});
			argvPtrs.push(0);

			const argv = offset;
			argvPtrs.forEach((ptr) => {
				this.mem.setUint32(offset, ptr, true);
				this.mem.setUint32(offset + 4, 0, true);
				offset += 8;
			});

			this._inst.exports.run(argc, argv);
			if (this.exited) {
				this._resolveExitPromise();
			}
			await this._exitPromise;
		}

		_resume() {
			if (this.exited) {
				throw new Error("Go program has already exited");
			}
			this._inst.exports.resume();
			if (this.exited) {
				this._resolveExitPromise();
			}
		}

		_makeFuncWrapper(id) {
			const go = this;
			return function () {
				const event = { id: id, this: this, args: arguments };
				go._pendingEvent = event;
				go._resume();
				return event.result;
			};
		}
	}

	if (
		global.require &&
		global.require.main === module &&
		global.process &&
		global.process.versions &&
		!global.process.versions.electron
	) {
		if (process.argv.length < 3) {
			console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
			process.exit(1);
		}

		const go = new Go();
		go.argv = process.argv.slice(2);
		go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
		go.exit = process.exit;
		WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
			process.on("exit", (code) => { // Node.js exits if no event handler is pending
				if (code === 0 && !go.exited) {
					// deadlock, make Go print error and stack traces
					go._pendingEvent = { id: 0 };
					go._resume();
				}
			});
			return go.run(result.instance);
		}).catch((err) => {
			console.error(err);
			process.exit(1);
		});
	}
})();


text:
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Converters
{
    internal class InputMediaConverter : InputFileConverter
    {
        public override bool CanConvert(Type objectType) => typeof(InputMedia) == objectType;

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var inputMediaType = (InputMedia)value;
            switch (inputMediaType.FileType)
            {
                case FileType.Id:
                case FileType.Url:
                    base.WriteJson(writer, value, serializer);
                    break;
                case FileType.Stream:
                    writer.WriteValue($"attach://{inputMediaType.FileName}");
                    break;
                default:
                    throw new NotSupportedException("File Type not supported");
            }
        }

        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            var value = JToken.ReadFrom(reader).Value<string>();

            if (value is null) { return null!; }

            return value.StartsWith("attach://", StringComparison.InvariantCulture)
                    ? new(Stream.Null, value.Substring(9))
                    : new InputMedia(value);
        }
    }
}


text:
import {Observable} from 'rxjs';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Injectable} from '@angular/core';

@Injectable(
  { providedIn: 'root'}
)
export class DirectAccessGuard implements CanActivate {
  constructor(private router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    // If the previous URL was blank, then the user is directly accessing this page
    if (this.router.url === '/') {
      this.router.navigate(['/catalogus']); // Navigate away to some other page
      return false;
    }
    return true;
  }
}


text:
using System.IO;

namespace SharpCompress.IO
{
    internal class RewindableStream : Stream
    {
        private readonly Stream stream;
        private MemoryStream bufferStream = new MemoryStream();
        private bool isRewound;
        private bool isDisposed;

        public RewindableStream(Stream stream)
        {
            this.stream = stream;
        }

        internal bool IsRecording { get; private set; }

        protected override void Dispose(bool disposing)
        {
            if (isDisposed)
            {
                return;
            }
            isDisposed = true;
            base.Dispose(disposing);
            if (disposing)
            {
                stream.Dispose();
            }
        }

        public void Rewind(bool stopRecording)
        {
            isRewound = true;
            IsRecording = !stopRecording;
            bufferStream.Position = 0;
        }

        public void Rewind(MemoryStream buffer)
        {
            if (bufferStream.Position >= buffer.Length)
            {
                bufferStream.Position -= buffer.Length;
            }
            else
            {
                //bufferStream.TransferTo(buffer);
                Utility.TransferTo(bufferStream,buffer);
                bufferStream = buffer;
                bufferStream.Position = 0;
            }
            isRewound = true;
        }

        public void StartRecording()
        {
            //if (isRewound && bufferStream.Position != 0)
            //   throw new System.NotImplementedException();
            if (bufferStream.Position != 0)
            {
                byte[] data = bufferStream.ToArray();
                long position = bufferStream.Position;
                bufferStream.SetLength(0);
                bufferStream.Write(data, (int)position, data.Length - (int)position);
                bufferStream.Position = 0;
            }
            IsRecording = true;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override void Flush()
        {
            throw new System.NotSupportedException();
        }

        public override long Length
        {
            get { throw new System.NotSupportedException(); }
        }

        public override long Position
        {
            get { return stream.Position + bufferStream.Position - bufferStream.Length; }
            set
            {
                if (!isRewound)
                {
                    stream.Position = value;
                }
                else if (value < stream.Position - bufferStream.Length || value >= stream.Position)
                {
                    stream.Position = value;
                    isRewound = false;
                    bufferStream.SetLength(0);
                }
                else
                {
                    bufferStream.Position = value - stream.Position + bufferStream.Length;
                }
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int read;
            if (isRewound && bufferStream.Position != bufferStream.Length)
            {
                read = bufferStream.Read(buffer, offset, count);
                if (read < count)
                {
                    int tempRead = stream.Read(buffer, offset + read, count - read);
                    if (IsRecording)
                    {
                        bufferStream.Write(buffer, offset + read, tempRead);
                    }
                    read += tempRead;
                }
                if (bufferStream.Position == bufferStream.Length && !IsRecording)
                {
                    isRewound = false;
                    bufferStream.SetLength(0);
                }
                return read;
            }

            read = stream.Read(buffer, offset, count);
            if (IsRecording)
            {
                bufferStream.Write(buffer, offset, read);
            }
            return read;
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new System.NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new System.NotSupportedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new System.NotSupportedException();
        }
    }
}


text:
package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import guitests.guihandles.HelpWindowHandle;

public class HelpWindowTest extends TodoListGuiTest {

    @Test
    public void openHelpWindow() {
        //use accelerator
        commandBox.clickOnTextField();
        assertHelpWindowOpen(mainMenu.openHelpWindowUsingAccelerator());

        resultDisplay.clickOnTextArea();
        assertHelpWindowOpen(mainMenu.openHelpWindowUsingAccelerator());

        taskListPanel.clickOnListView();
        assertHelpWindowOpen(mainMenu.openHelpWindowUsingAccelerator());

        //use menu button
        assertHelpWindowOpen(mainMenu.openHelpWindowUsingMenu());

        //use command
        assertHelpWindowOpen(commandBox.runHelpCommand("help"));
        assertHelpWindowOpen(commandBox.runHelpCommand("helps"));
        assertHelpWindowOpen(commandBox.runHelpCommand("h"));
        assertHelpWindowOpen(commandBox.runHelpCommand("manual"));
        assertHelpWindowOpen(commandBox.runHelpCommand("instructions"));
        assertHelpWindowOpen(commandBox.runHelpCommand("instruction"));
    }

    private void assertHelpWindowOpen(HelpWindowHandle helpWindowHandle) {
        assertTrue(helpWindowHandle.isWindowOpen());
        helpWindowHandle.closeWindow();
    }
}


text:
<?php

?>

<?php echo $projects->getName() ?>

      <?php if($projects->getProjectsStatusId()>0) echo '
' . __('Status') . ': ' . $projects->getProjectsStatus()->getName() . '
	';?>
      <?php if($projects->getProjectsTypesId()>0) echo '
' . __('Type') . ': ' . $projects->getProjectsTypes()->getName() . '
	';?>

      <?php echo link_to_modalbox(__('More Info'),'projects/info?id=' . $projects->getId()) ?>
      <?php if(Users::hasAccess('edit','projects',$sf_user,$projects->getId())) echo link_to_modalbox(__('Edit Details'),'projects/edit?id=' . $projects->getId() . '&redirect_to=projectsComments') ?>

    <?php $m = new projectsMenuController($sf_user,$sf_request); echo renderYuiMenu('projectMenu',$m->buildMenu($sf_context)) ?>


text:
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class Latitude19Gateway < Gateway
      self.display_name = 'Latitude19 Gateway'
      self.homepage_url = 'http://www.l19tech.com'

      self.live_url = 'https://gateway.l19tech.com/payments/'
      self.test_url = 'https://gateway-sb.l19tech.com/payments/'

      self.supported_countries = %w[US CA]
      self.default_currency = 'USD'
      self.money_format = :dollars
      self.supported_cardtypes = %i[visa master american_express discover diners_club jcb]

      RESPONSE_CODE_MAPPING = {
        '100' => 'Approved',
        '101' => 'Local duplicate detected',
        '102' => 'Accepted local capture with no match',
        '103' => 'Auth succeeded but capture failed',
        '104' => 'Auth succeeded but failed to save info',
        '200' => STANDARD_ERROR_CODE[:card_declined],
        '300' => 'Processor reject',
        '301' => 'Local reject on user/password',
        '302' => 'Local reject',
        '303' => 'Processor unknown response',
        '304' => 'Error parsing processor response',
        '305' => 'Processor auth succeeded but settle failed',
        '306' => 'Processor auth succeeded settle status unknown',
        '307' => 'Processor settle status unknown',
        '308' => 'Processor duplicate',
        '400' => 'Not submitted',
        '401' => 'Terminated before request submitted',
        '402' => 'Local server busy',
        '500' => 'Submitted not returned',
        '501' => 'Terminated before response returned',
        '502' => 'Processor returned timeout status',
        '600' => 'Failed local capture with no match',
        '601' => 'Failed local capture',
        '700' => 'Failed local void (not in capture file)',
        '701' => 'Failed local void',
        '800' => 'Failed local refund (not authorized)',
        '801' => 'Failed local refund'
      }

      BRAND_MAP = {
        'master' => 'MC',
        'visa' => 'VI',
        'american_express' => 'AX',
        'discover' => 'DS',
        'diners_club' => 'DC',
        'jcb' => 'JC'
      }

      def initialize(options = {})
        requires!(options, :account_number, :configuration_id, :secret)
        super
      end

      def purchase(amount, payment_method, options = {})
        if payment_method.is_a?(String)
          auth_or_sale('sale', payment_method, amount, nil, options)
        else
          MultiResponse.run() do |r|
            r.process { get_session(options) }
            r.process { get_token(r.authorization, payment_method, options) }
            r.process { auth_or_sale('sale', r.authorization, amount, payment_method, options) }
          end
        end
      end

      def authorize(amount, payment_method, options = {})
        if payment_method.is_a?(String)
          auth_or_sale('auth', payment_method, amount, nil, options)
        else
          MultiResponse.run() do |r|
            r.process { get_session(options) }
            r.process { get_token(r.authorization, payment_method, options) }
            r.process { auth_or_sale('auth', r.authorization, amount, payment_method, options) }
          end
        end
      end

      def capture(amount, authorization, options = {})
        post = {}
        post[:method] = 'deposit'
        add_request_id(post)

        params = {}

        _, params[:pgwTID] = split_authorization(authorization)

        add_invoice(params, amount, options)
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('v1/', post)
      end

      def void(authorization, options = {})
        method, pgwTID = split_authorization(authorization)
        case method
        when 'auth'
          reverse_or_void('reversal', pgwTID, options)
        when 'deposit', 'sale'
          reverse_or_void('void', pgwTID, options)
        else
          message = 'Unsupported operation: successful Purchase, Authorize and unsettled Capture transactions can only be voided.'
          return Response.new(false, message)
        end
      end

      def credit(amount, payment_method, options = {})
        if payment_method.is_a?(String)
          refundWithCard(payment_method, amount, nil, options)
        else
          MultiResponse.run() do |r|
            r.process { get_session(options) }
            r.process { get_token(r.authorization, payment_method, options) }
            r.process { refundWithCard(r.authorization, amount, payment_method, options) }
          end
        end
      end

      def verify(payment_method, options = {}, action = nil)
        if payment_method.is_a?(String)
          verifyOnly(action, payment_method, nil, options)
        else
          MultiResponse.run() do |r|
            r.process { get_session(options) }
            r.process { get_token(r.authorization, payment_method, options) }
            r.process { verifyOnly(action, r.authorization, payment_method, options) }
          end
        end
      end

      def store(payment_method, options = {})
        verify(payment_method, options, 'store')
      end

      def supports_scrubbing?
        true
      end

      def scrub(transcript)
        transcript.
          gsub(%r((\"cardNumber\\\":\\\")\d+), '\1[FILTERED]').
          gsub(%r((\"cvv\\\":\\\")\d+), '\1[FILTERED]')
      end

      private

      def add_request_id(post)
        post[:id] = SecureRandom.hex(16)
      end

      def add_timestamp
        Time.now.getutc.strftime('%Y%m%d%H%M%S')
      end

      def add_hmac(params, method)
        if method == 'getSession'
          hmac_message = params[:pgwAccountNumber] + '|' + params[:pgwConfigurationId] + '|' + params[:requestTimeStamp] + '|' + method
        else
          hmac_message = params[:pgwAccountNumber] + '|' + params[:pgwConfigurationId] + '|' + (params[:orderNumber] || '') + '|' + method + '|' + (params[:amount] || '') + '|' + (params[:sessionToken] || '') + '|' + (params[:accountToken] || '')
        end

        OpenSSL::HMAC.hexdigest('sha512', @options[:secret], hmac_message)
      end

      def add_credentials(params, method)
        params[:pgwAccountNumber] = @options[:account_number]
        params[:pgwConfigurationId] = @options[:configuration_id]

        params[:requestTimeStamp] = add_timestamp() if method == 'getSession'

        params[:pgwHMAC] = add_hmac(params, method)
      end

      def add_invoice(params, money, options)
        params[:amount] = amount(money)
        params[:orderNumber] = options[:order_id]
        params[:transactionClass] = options[:transaction_class] || 'eCommerce'
      end

      def add_payment_method(params, credit_card)
        params[:cardExp] = format(credit_card.month, :two_digits).to_s + '/' + format(credit_card.year, :two_digits).to_s
        params[:cardType] = BRAND_MAP[credit_card.brand.to_s]
        params[:cvv] = credit_card.verification_value
        params[:firstName] = credit_card.first_name
        params[:lastName] = credit_card.last_name
      end

      def add_customer_data(params, options)
        if (billing_address = options[:billing_address] || options[:address])
          params[:address1] = billing_address[:address1]
          params[:address2] = billing_address[:address2]
          params[:city] = billing_address[:city]
          params[:stateProvince] = billing_address[:state]
          params[:zipPostalCode] = billing_address[:zip]
          params[:countryCode] = billing_address[:country]
        end
      end

      def get_session(options = {})
        post = {}
        post[:method] = 'getSession'
        add_request_id(post)

        params = {}
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('session', post)
      end

      def get_token(authorization, payment_method, options = {})
        post = {}
        post[:method] = 'tokenize'
        add_request_id(post)

        params = {}
        _, params[:sessionId] = split_authorization(authorization)
        params[:cardNumber] = payment_method.number

        post[:params] = [params]
        commit('token', post)
      end

      def auth_or_sale(method, authorization, amount, credit_card, options = {})
        post = {}
        post[:method] = method
        add_request_id(post)

        params = {}
        if credit_card
          _, params[:sessionToken] = split_authorization(authorization)
          add_payment_method(params, credit_card)
          add_customer_data(params, options)
        else
          _, params[:accountToken] = split_authorization(authorization)
        end
        add_invoice(params, amount, options)
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('v1/', post)
      end

      def verifyOnly(action, authorization, credit_card, options = {})
        post = {}
        post[:method] = 'verifyOnly'
        add_request_id(post)

        params = {}
        if credit_card
          _, params[:sessionToken] = split_authorization(authorization)
          add_payment_method(params, credit_card)
          add_customer_data(params, options)
        else
          _, params[:accountToken] = split_authorization(authorization)
        end
        params[:requestAccountToken] = '1' if action == 'store'
        add_invoice(params, 0, options)
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('v1/', post)
      end

      def refundWithCard(authorization, amount, credit_card, options = {})
        post = {}
        post[:method] = 'refundWithCard'
        add_request_id(post)

        params = {}
        if credit_card
          _, params[:sessionToken] = split_authorization(authorization)
          add_payment_method(params, credit_card)
        else
          _, params[:accountToken] = split_authorization(authorization)
        end
        add_invoice(params, amount, options)
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('v1/', post)
      end

      def reverse_or_void(method, pgwTID, options = {})
        post = {}
        post[:method] = method
        add_request_id(post)

        params = {}
        params[:orderNumber] = options[:order_id]
        params[:pgwTID] = pgwTID
        add_credentials(params, post[:method])

        post[:params] = [params]
        commit('v1/', post)
      end

      def commit(endpoint, post)
        raw_response = ssl_post(url() + endpoint, post_data(post), headers)
        response = parse(raw_response)
      rescue ResponseError => e
        raw_response = e.response.body
        response_error(raw_response)
      rescue JSON::ParserError
        unparsable_response(raw_response)
      else
        success = success_from(response)
        Response.new(
          success,
          message_from(response),
          response,
          authorization: success ? authorization_from(response, post[:method]) : nil,
          avs_result: success ? avs_from(response) : nil,
          cvv_result: success ? cvv_from(response) : nil,
          error_code: success ? nil : error_from(response),
          test: test?
        )
      end

      def headers
        {
          'Content-Type' => 'application/json'
        }
      end

      def post_data(params)
        params.to_json
      end

      def url
        test? ? test_url : live_url
      end

      def parse(body)
        JSON.parse(body)
      end

      def success_from(response)
        return false if response['result'].nil? || response['error']

        if response['result'].key?('pgwResponseCode')
          response['error'].nil? && response['result']['lastActionSucceeded'] == 1 && response['result']['pgwResponseCode'] == '100'
        else
          response['error'].nil? && response['result']['lastActionSucceeded'] == 1
        end
      end

      def message_from(response)
        return response['error'] if response['error']
        return 'Failed' unless response.key?('result')

        if response['result'].key?('pgwResponseCode')
          RESPONSE_CODE_MAPPING[response['result']['pgwResponseCode']] || response['result']['responseText']
        else
          response['result']['lastActionSucceeded'] == 1 ? 'Succeeded' : 'Failed'
        end
      end

      def error_from(response)
        return response['error'] if response['error']
        return 'Failed' unless response.key?('result')

        return response['result']['pgwResponseCode'] || response['result']['processor']['responseCode'] || 'Failed'
      end

      def authorization_from(response, method)
        method + '|' + (
          response['result']['sessionId'] ||
          response['result']['sessionToken'] ||
          response['result']['pgwTID'] ||
          response['result']['accountToken']
        )
      end

      def split_authorization(authorization)
        authorization.split('|')
      end

      def avs_from(response)
        response['result'].key?('avsResponse') ? AVSResult.new(code: response['result']['avsResponse']) : nil
      end

      def cvv_from(response)
        response['result'].key?('cvvResponse') ? CVVResult.new(response['result']['cvvResponse']) : nil
      end

      def response_error(raw_response)
        response = parse(raw_response)
      rescue JSON::ParserError
        unparsable_response(raw_response)
      else
        return Response.new(
          false,
          message_from(response),
          response,
          test: test?
        )
      end

      def unparsable_response(raw_response)
        message = 'Invalid JSON response received from Latitude19Gateway. Please contact Latitude19Gateway if you continue to receive this message.'
        message += " (The raw response returned by the API was #{raw_response.inspect})"
        return Response.new(false, message)
      end
    end
  end
end


text:
namespace Microsoft.Azure.Management.Compute.Models
{
    using Azure;
    using Management;
    using Compute;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for SettingNames.
    /// </summary>
    [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public enum SettingNames
    {
        [EnumMember(Value = "AutoLogon")]
        AutoLogon,
        [EnumMember(Value = "FirstLogonCommands")]
        FirstLogonCommands
    }
}


text:
<?php
/**
 * @file
 * Contains \Drupal\suffix_main\Controller\NeedController.
 */
namespace Drupal\suffix_main\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\suffix_main\Controller\OrderController;
use Drupal\suffix_main\ApplyStorage;
use Drupal\suffix_main\ProductStorage;
use Drupal\suffix_main\NeedStorage;
use Drupal\suffix_main\UserStorage;
use Drupal\suffix_main\OrderStorage;

class NeedController extends APIBaseController {

    public function __construct()
    {
    }

    public function add_need(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'apply_id'=>array(
                'rule'=>'require',
                'declare'=>'报名号'
            ),
            'product_id'=>array(
                'rule'=>'all|number',
                'declare'=>'产品ID'
            ),
            'add_name'=>array(
                'rule'=>'all',
                'declare'=>'操作人'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $insertData = $this->getDefaultValue();
        $insertData['apply_id'] = intval($queryData['apply_id']);
        $insertData['product_id'] = $queryData['product_id']?intval($queryData['product_id']):null;
        $applyInfo = ApplyStorage::getApplyInfo(array('apply_id'=>intval($queryData['apply_id'])));
        if(!$applyInfo){
            $this->error('预约信息错误');
        }
        $applyInfo = $this->json_deal($applyInfo);
        $insertData['user_id'] = $applyInfo['uid'];
        $insertData['username'] = $applyInfo['username'];
        $insertData['mobile'] = $applyInfo['mobile'];
        $insertData['province'] = $applyInfo['province'];
        $insertData['city'] = $applyInfo['city'];
        $insertData['district'] = $applyInfo['district'];
        $insertData['address'] = $applyInfo['address'];
        $insertData['longitude'] = $applyInfo['longitude'];
        $insertData['latitude'] = $applyInfo['latitude'];
        $insertData['remark'] = $applyInfo['remark'];
        if($queryData['product_id']) {
            $productInfo = ProductStorage::getProductInfo(intval($queryData['product_id']));
            if (!$productInfo) {
                $this->error('产品信息错误');
            }
        }
        if($queryData['add_name']){
            $insertData['create_user'] = $queryData['create_user'];
            $insertData['modify_user'] = $queryData['modify_user'];
        }
        $res = NeedStorage::insertNeedInfo($insertData);
        $return = array('need_id'=>$res);
        if(false) {
            $orderId = $this->assignOrder($res); //自动分单逻辑
            if ($orderId) {
                $return['order_id'] = $orderId;
                //改变需求状态逻辑
                NeedStorage::updateNeedInfo('need_id',array('need_id' => intval($res), 'status' => 2));
            }
        }

        $this->success($return);
    }

    public function getProductKind(){
        $list = ProductStorage::getProductKind();
        $this->success($list);
    }

    public function getProductDetail(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'product_id'=>array(
                'rule'=>'require',
                'declare'=>'产品ID'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $productInfo = ProductStorage::getProductInfo(intval($queryData['product_id']));
        $this->success($productInfo);
    }

    public function getProductList(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'type'=>array(
                'rule'=>'require',
                'declare'=>'分类'
            ),
//            'online'=>array(
//                'rule'=>'all|number',
//                'declare'=>'是否上架',
//                'default'=>0
//            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $list = ProductStorage::getProductList(array('type'=>$queryData['type'],'deleted'=>0));
        $this->success($list);
    }

    public function edit_need(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'need_id'=>array(
                'rule'=>'require',
                'declare'=>'需求ID'
            ),
            'status'=>array(
                'rule'=>'all|number',
                'declare'=>'状态'
            ),
            'modify_user'=>array(
                'rule'=>'all',
                'declare'=>'操作人'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $res = NeedStorage::updateNeedInfo('need_id',$queryData);
        $this->success($res);
    }

    function testSql(){
        $sql = "UPDATE {sessions} SET sid = '' WHERE uid = :uid";
        var_export(NeedStorage::sqlSearch($sql));
    }

    private function getDefaultValue(){//补全插入数据字段
        return array(
            'user_id' => null,
            'apply_id' => null,
            'product_id' => null,
            'username'=>'',
            'mobile'=>'13200020001',
            'province' => '',
            'city' => '',
            'district' => '',
            'address' => '',
            'longitude' => '',
            'latitude' => '',
            'remark' => '',
            'status' => 1,
            'create_time' => time(),
            'create_user' => '',
            'modify_time' => time(),
            'modify_user' => '',
        );
    }

    private function validateRule(){
        return array();
    }

    private function assignOrder($need_id){
//        die;
        $return  = null;
        $shopList = UserStorage::getUserListByRole();
        if($shopList){
            $shopList = $this->json_deal($shopList);
            $shopId = $shopList[0]['uid'];
            $return  = $this->autoAddOrder($need_id,$shopId);
        }
        return $return;
    }

    public function getShopList(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'name'=>array(
                'rule'=>'all',
                'declare'=>'用户名'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $shopList = UserStorage::getUserListByRole($queryData['name']);
        $this->success($shopList);
    }

    public function autoAddOrder($need_id,$shopId){
        $insertData = OrderController::getDefaultValue();
        $needInfo = NeedStorage::getNeedInfo(array('need_id'=>intval($need_id)));
        if(!$needInfo){
            $this->error('需求信息有误');
        }
        $shopInfo = UserStorage::getOneUserByUid(intval($shopId));
        if(!$shopInfo){
            $this->error('商家信息有误');
        }
        $needInfo = $this->json_deal($needInfo);
        $insertData['user_id'] = $needInfo['user_id'];
        $insertData['accept_id'] = intval($shopId);
        $insertData['apply_id'] = $needInfo['apply_id'];
        $insertData['need_id'] = $needInfo['need_id'];
        $insertData['province'] = $needInfo['province'];
        $insertData['city'] = $needInfo['city'];
        $insertData['district'] = $needInfo['district'];
        $insertData['remark'] = $needInfo['remark'];
        $orderId = OrderStorage::insertOrderInfo($insertData);
        return $orderId?:null;
    }

    function  getUserInfo(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'uid'=>array(
                'rule'=>'require',
                'declare'=>'用户id'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $info = UserStorage::getOneUserByUid($queryData['uid']);
        $this->success($info);
    }

}


text:
const path = require('path')

const appPath = (...names) => path.join(process.cwd(), ...names)

//This will be merged with the config from the flavor
module.exports = {
    entry: {
        main: [appPath('src', 'index.ts'), appPath('src', 'css', 'styles.scss')]
    },
    output: {
        filename: 'bundle.[hash].js',
        path: appPath('build')
    }
}


text:
package com.excilys.ebi.utils.spring.log.logback.web;

import java.io.FileNotFoundException;

import javax.servlet.ServletContext;

import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.WebUtils;

import ch.qos.logback.core.joran.spi.JoranException;

import com.excilys.ebi.utils.spring.log.logback.LogbackConfigurer;

/**
 * Convenience class that performs custom Logback initialization for web
 * environments, allowing for log file paths within the web application,
 * inspired by {@link org.springframework.web.util.Log4jWebConfigurer}.
 *

 * Supports an init parameter at the servlet context level (that is,
 * context-param entries in web.xml):
 *

 *
"logbackConfigLocation":

 * Location of the Logback config file; either a "classpath:" location (e.g.
 * "classpath:myLogback.xml"), an absolute file URL (e.g.
 * "file:C:/logback.properties), or a plain path relative to the web application
 * root directory (e.g. "/WEB-INF/logback.xml"). If not specified, default
 * Logback initialization will apply ("logback.xml" or "logback-test.xml" in the
 * class path; see Logback documentation for details).
 *

 *

 * Note: initLogging should be called before any other Spring
 * activity (when using Logback), for proper initialization before any Spring
 * logging attempts.
 *

 *
 * @author Stephane LANDELLE
 */
public final class LogbackWebConfigurer {

	/** Parameter specifying the location of the logback config file. */
	public static final String CONFIG_LOCATION_PARAM = "logbackConfigLocation";

	/**
	 * Instantiates a new logback web configurer.
	 */
	private LogbackWebConfigurer() {
	}

	/**
	 * Initialize Logback, including setting the web app root system property.
	 *
	 * @param servletContext
	 *            the current ServletContext
	 * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty
	 */
	public static void initLogging(ServletContext servletContext) {

		// Only perform custom Logback initialization in case of a config file.
		String location = getConfigLocation(servletContext);

		if (location != null) {
			// Perform actual Logback initialization; else rely on Logback's
			// default initialization.
			try {
				// Return a URL (e.g. "classpath:" or "file:") as-is;
				// consider a plain file path as relative to the web application
				// root directory.
				if (!ResourceUtils.isUrl(location)) {
					// Resolve system property placeholders before resolving
					// real path.
					location = SystemPropertyUtils.resolvePlaceholders(location);
					location = WebUtils.getRealPath(servletContext, location);
				}

				// Write log message to server log.
				servletContext.log("Initializing Logback from [" + location + "]");

				// Initialize
				LogbackConfigurer.initLogging(location);
			} catch (FileNotFoundException ex) {
				throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
			} catch (JoranException e) {
				throw new RuntimeException("Unexpected error while configuring logback", e);
			}
		}
	}

	/**
	 * Search for a specified config location, first in the servlet context and
	 * then as a System property
	 *
	 * @param servletContext
	 *            the servletContext
	 * @return the config location
	 */
	private static String getConfigLocation(ServletContext servletContext) {
		String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
		if (location == null) {
			location = System.getProperty(CONFIG_LOCATION_PARAM);
		}
		return location;
	}

	/**
	 * Shut down Logback, properly releasing all file locks and resetting the
	 * web app root system property.
	 *
	 * @param servletContext
	 *            the current ServletContext
	 * @see WebUtils#removeWebAppRootSystemProperty
	 */
	public static void shutdownLogging(ServletContext servletContext) {
		servletContext.log("Shutting down Logback");
		LogbackConfigurer.shutdownLogging();
	}
}


text:
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

from test import Banana

graphviz = GraphvizOutput(output_file='filter_none.png')

with PyCallGraph(output=graphviz):
    banana = Banana()
    banana.eat()


text:
import React, {
  Text,
  StyleSheet,
  Component,
} from 'react-native';

import Button from './Button';

export default class ScoreButton extends Component {
  render() {
    return(
      <Button
        buttonStyle={styles.button}
        onPress={this.props.onClick}
        text={this.props.score}
        buttonTextStyle={styles.buttonText} />
    );
  }
}

var styles = StyleSheet.create({
  button: {
    height: 100,
    borderRadius: 50,
    width: 100,
    margin: 10,
  },
  buttonText: {
    fontSize: 40,
    marginTop: 20,
    marginLeft: 5,
    alignSelf: 'center'
  }
});