text:
@interface WLCurrentUserHelper ()

@property (nonatomic, strong, readonly) id propertiesChanged;

@end

@implementation WLCurrentUserHelper

#pragma mark - Lifecycle

+ (instancetype)user {

    static dispatch_once_t onceToken;
    static id sharedInstance = nil;

    dispatch_once(&onceToken, ^{
        sharedInstance = [self instanceFromDefaults] ?: [[self alloc] init];
    });

    return sharedInstance;
}

- (instancetype)init {
    self = [super init];

    [self addObserver:self
           forKeyPath:@"propertiesChanged"
              options:NSKeyValueObservingOptionNew
              context:nil];

    return self;
}

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"propertiesChanged"];
}

- (void)copyPropertiesFromInstance:(id)instance {

    // Decode properties, other class vars
    NSDictionary *propertyDict = [WLUtilityHelper propertiesForClass:[self class]];

    // Retrieve excluded properties
    NSArray *excludedProperties = [[self excludedProperties] arrayByAddingObject:@"propertiesChanged"];

    for (NSString *key in propertyDict) {
        if (!excludedProperties || ![excludedProperties containsObject:key]) {
            id value = [instance valueForKey:key];
            [self setValue:value forKey:key];
        }
    }
}

#pragma mark - Archiveable

- (NSArray *)excludedProperties {
    // Override point
    return @[];
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    // Encode properties, other class variables, etc
    NSDictionary *propertyDict = [WLUtilityHelper propertiesForClass:[self class]];

    // Retrieve excluded properties
    NSArray *excludedProperties = [[self excludedProperties] arrayByAddingObject:@"propertiesChanged"];

    for (NSString *key in propertyDict) {
        if (!excludedProperties || ![excludedProperties containsObject:key]) {
            id value = [self valueForKey:key];
            [encoder encodeObject:value forKey:key];
        }
    }
}

- (instancetype)initWithCoder:(NSCoder *)decoder {
    if([self init]) {
        // Decode properties, other class vars
        NSDictionary *propertyDict = [WLUtilityHelper propertiesForClass:[self class]];

        // Retrieve excluded properties
        NSArray *excludedProperties = [[self excludedProperties] arrayByAddingObject:@"propertiesChanged"];

        for (NSString *key in propertyDict) {
            if (!excludedProperties || ![excludedProperties containsObject:key]) {
                id value = [decoder decodeObjectForKey:key];
                [self setValue:value forKey:key];
            }
        }
    }
    return self;
}

#pragma mark - Key-value observing

- (id)propertiesChanged {
    return nil;
}

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context {
    // Save new instance to defaults
    [self saveToDefauls];
}

+(NSSet *)keyPathsForValuesAffectingPropertiesChanged {
    NSMutableArray *properties = [[[WLUtilityHelper propertiesForClass:[self class]] allKeys] mutableCopy];
    [properties removeObject:@"propertiesChanged"];

    return [NSSet setWithArray:properties];
}

#pragma mark - Defaults

+ (id)instanceFromDefaults {
    NSData *encodedObject = [WLUtilityHelper dataFromDefaultsWithKey:WLCurrentUserDefaultsKey];
    id instance = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];

    if ([instance isKindOfClass:self]) {
        return instance;
    } else {
        return nil;
    }
}

- (void)saveToDefauls {
    NSData *encoded = [NSKeyedArchiver archivedDataWithRootObject:self];
    [WLUtilityHelper writeDataToDefaults:encoded forKey:WLCurrentUserDefaultsKey];
}

+ (void)cleanDefaultsSaveFields:(NSArray *)fields {
    // Saved specified fields
    NSMutableDictionary *fieldsDict = [NSMutableDictionary new];

    id currentUser = [self instanceFromDefaults];
    for (id field in fields) {
        if ([currentUser respondsToSelector:NSSelectorFromString(field)] &&
            [currentUser valueForKey:field]) {
            [fieldsDict setObject:[currentUser valueForKey:field] forKey:field];
        }
    }

    // Clean up all defaults data
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [defaults removePersistentDomainForName:appDomain];
    [defaults synchronize];

    // Add specified fields back
    id newCurrentUser = [[self alloc] init];
    for (id fieldKey in [fieldsDict allKeys]) {
        if ([newCurrentUser respondsToSelector:NSSelectorFromString(fieldKey)]) {
            [newCurrentUser setValue:fieldsDict[fieldKey] forKey:fieldKey];
        }
    }

    [newCurrentUser saveToDefauls];

    // Reflect changes in current extracted object
    if ([self instanceFromDefaults]) {
        [[self user] copyPropertiesFromInstance:[self instanceFromDefaults]];
    }
}

@end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Tutorials on Columbia Psychology Scientific Computing</title>
    <link>/tutorials/</link>
    <description>Recent content in Tutorials on Columbia Psychology Scientific Computing</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>

	<atom:link href="/tutorials/index.xml" rel="self" type="application/rss+xml" />

  </channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
"""
Facebook platform for notify component.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.facebook/
"""
import logging

import requests

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (
    ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService)
from homeassistant.const import CONTENT_TYPE_JSON

_LOGGER = logging.getLogger(__name__)

CONF_PAGE_ACCESS_TOKEN = 'page_access_token'
BASE_URL = 'https://graph.facebook.com/v2.6/me/messages'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_PAGE_ACCESS_TOKEN): cv.string,
})

def get_service(hass, config):
    """Get the Facebook notification service."""
    return FacebookNotificationService(config[CONF_PAGE_ACCESS_TOKEN])

class FacebookNotificationService(BaseNotificationService):
    """Implementation of a notification service for the Facebook service."""

    def __init__(self, access_token):
        """Initialize the service."""
        self.page_access_token = access_token

    def send_message(self, message="", **kwargs):
        """Send some message."""
        payload = {'access_token': self.page_access_token}
        targets = kwargs.get(ATTR_TARGET)

        if not targets:
            _LOGGER.error("At least 1 target is required")
            return

        for target in targets:
            body = {
                "recipient": {"phone_number": target},
                "message": {"text": message}
            }
            import json
            resp = requests.post(BASE_URL, data=json.dumps(body),
                                 params=payload,
                                 headers={'Content-Type': CONTENT_TYPE_JSON},
                                 timeout=10)
            if resp.status_code != 200:
                obj = resp.json()
                error_message = obj['error']['message']
                error_code = obj['error']['code']
                _LOGGER.error("Error %s : %s (Code %s)", resp.status_code,
                              error_message,
                              error_code)


text:
<?php

/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

if (empty($lang) || !is_array($lang))
{
	$lang = array();
}

// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine

$lang = array_merge($lang, array(
	'ACP_MODULE_MANAGEMENT_EXPLAIN'	=> 'Здесь вы можете управлять всеми типами модулей. Обратите внимание на то, что администраторский раздел имеет трёхуровневую структуру меню (Категория → Категория → Модуль), в результате чего подразделы имеют двухуровневую структуру меню (Категория → Модуль), которая должна быть сохранена. Также учтите, что вы можете заблокировать доступ самому себе, если вы отключите или удалите модули, отвечающие за управление модулями.',
	'ADD_MODULE'					=> 'Добавить модуль',
	'ADD_MODULE_CONFIRM'			=> 'Вы действительно хотите добавить выбранный модуль с указанным методом использования?',
	'ADD_MODULE_TITLE'				=> 'Добавление модуля',

	'CANNOT_REMOVE_MODULE'	=> 'Не удалось удалить модуль, поскольку на него назначены дочерние модули. Удалите или переместите все дочерние модули перед выполнением этого действия.',
	'CATEGORY'				=> 'Категория',
	'CHOOSE_MODE'			=> 'Метод использования модуля',
	'CHOOSE_MODE_EXPLAIN'	=> 'Выберите метод использования модуля.',
	'CHOOSE_MODULE'			=> 'Выбор модуля',
	'CHOOSE_MODULE_EXPLAIN'	=> 'Выберите файл, вызываемый данным модулем.',
	'CREATE_MODULE'			=> 'Создать модуль',

	'DEACTIVATED_MODULE'	=> 'Отключённый модуль',
	'DELETE_MODULE'			=> 'Удалить модуль',
	'DELETE_MODULE_CONFIRM'	=> 'Вы действительно хотите удалить этот модуль?',

	'EDIT_MODULE'			=> 'Настройка модуля',
	'EDIT_MODULE_EXPLAIN'	=> 'С помощью этой страницы вы можете настроить модуль.',

	'HIDDEN_MODULE'			=> 'Скрытый модуль',

	'MODULE'					=> 'Модуль',
	'MODULE_ADDED'				=> 'Модуль успешно добавлен.',
	'MODULE_DELETED'			=> 'Модуль успешно удалён.',
	'MODULE_DISPLAYED'			=> 'Отображение модуля',
	'MODULE_DISPLAYED_EXPLAIN'	=> 'Если вы не хотите, чтобы модуль отображался в списке, но хотите использовать его, то установите переключатель в положение «Нет».',
	'MODULE_EDITED'				=> 'Настройки модуля успешно изменены.',
	'MODULE_ENABLED'			=> 'Модуль включён',
	'MODULE_LANGNAME'			=> 'Имя модуля',
	'MODULE_LANGNAME_EXPLAIN'	=> 'Введите отображаемое имя модуля. Используйте имя переменной, если имя модуля объявлено в языковом файле.',
	'MODULE_TYPE'				=> 'Тип модуля',

	'NO_CATEGORY_TO_MODULE'	=> 'Не удалось объявить категорию модулем. Удалите или переместите все дочерние модули перед выполнением этого действия.',
	'NO_MODULE'				=> 'Модуль не найден.',
	'NO_MODULE_ID'			=> 'Не указан ID модуля.',
	'NO_MODULE_LANGNAME'	=> 'Не указано имя модуля.',
	'NO_PARENT'				=> 'Нет родителя',

	'PARENT'				=> 'Родитель',
	'PARENT_NO_EXIST'		=> 'Родитель не существует.',

	'SELECT_MODULE'			=> 'Выберите модуль',
));

?>


text:
package com.intellij.codeInsight.template.macro;

import com.intellij.codeInsight.template.Expression;
import com.intellij.codeInsight.template.ExpressionContext;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiUtilCore;

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

/**
 * @author Konstantin Bulenkov
 */
public class SuggestFirstVariableNameMacro extends VariableOfTypeMacro {
  @Override
  public String getName() {
    return "suggestFirstVariableName";
  }

  @Override
  protected PsiElement[] getVariables(Expression[] params, ExpressionContext context) {
    final PsiElement[] variables = super.getVariables(params, context);
    if (variables == null) return null;
    final List<PsiElement> result = new ArrayList<>();
    final List<String> skip = Arrays.asList("true", "false", "this", "super");
    for (PsiElement variable : variables) {
      if (!skip.contains(variable.getText())) {
        result.add(variable);
      }
    }
    return PsiUtilCore.toPsiElementArray(result);
  }
}


text:
/* Language-independent unwinder header public defines.  This contains both
   ABI defined objects, and GNU support routines.  */

#ifndef UNWIND_C6X_H
#define UNWIND_C6X_H

/* Not really the ARM EABI, but pretty close.  */
#include "unwind-arm-common.h"

#define UNWIND_STACK_REG 31
/* Use A0 as a scratch register within the personality routine.  */
#define UNWIND_POINTER_REG 0

#ifdef __cplusplus
extern "C" {
#endif
  _Unwind_Reason_Code __gnu_unwind_24bit (_Unwind_Context *, _uw, int);

  /* Decode an EH table reference to a typeinfo object.  */
  static inline _Unwind_Word
  _Unwind_decode_typeinfo_ptr (_Unwind_Ptr base, _Unwind_Word ptr)
    {
      _Unwind_Word tmp;

      tmp = *(_Unwind_Word *) ptr;
      /* Zero values are always NULL.  */
      if (!tmp)
	return 0;

      /* SB-relative indirect.  Propagate the bottom 2 bits, which can
	 contain referenceness information in gnu unwinding tables.  */
      tmp += base;
      tmp = *(_Unwind_Word *) (tmp & ~(_Unwind_Word)3) | (tmp & 3);
      return tmp;
    }

#define _Unwind_GetIP(context) \
  (_Unwind_GetGR (context, 33))

#define _Unwind_SetIP(context, val) \
  _Unwind_SetGR (context, 33, val)

#ifdef __cplusplus
}   /* extern "C" */
#endif

#endif /* defined UNWIND_ARM_H */


text:
cordova.define("org.apache.cordova.core.file.LocalFileSystem", function(require, exports, module) {

var exec = require('cordova/exec');

/**
 * Represents a local file system.
 */
var LocalFileSystem = function() {

};

LocalFileSystem.TEMPORARY = 0; //temporary, with no guarantee of persistence
LocalFileSystem.PERSISTENT = 1; //persistent

module.exports = LocalFileSystem;
});


text:
"use strict";

export default {

  // User
  LOGIN: "login",
  LOGIN_PENDING: "login_pending",
  REGISTER: "register",
  REGISTER_PENDING: "register_pending",

  // Errors
  TIMEOUT: "timeout",
  ERROR: "error",
  NOT_AUTHORIZED: "not_authorized",

  // settings
  SETTINGS_LOAD: "settings_load",
  USER_LOAD: "user_load"

};


text:
package com.vanlanschot.services.documents;

/**
 * Created by dannykruitbosch on 24/10/16.
 */

import com.typesafe.config.Config;
import com.vanlanschot.services.model.Error;
import com.vanlanschot.services.model.Metadata;
import com.vanlanschot.services.model.Upload;
import io.swagger.annotations.*;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.msf4j.template.MustacheTemplateEngine;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Base64;
import javax.ws.rs.*;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static java.nio.file.StandardOpenOption.*;

/**
 * Simple DocumentService Class.
 *
 */
@SwaggerDefinition(
        info = @Info(title = "Documentum Service", version = "1.0.0", description = "This service allows you to upload documents")
)
@Path("/documentum")
public class DocumentService {

    private  Config config;

    // Constructor
    public DocumentService(Config config) {
        this.config = config;
    }
    private static final Logger log = LoggerFactory.getLogger(DocumentService.class);

    @POST
    @Path("/upload")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(
            value = "Upload",
            notes = "You can add metadata to the upload by passing a valid metadata json object")
    public Response uploadFile(@ApiParam(name = "Upload object", required = true) Upload upload) throws Exception {

        String STORAGE_PATH = config.getString("storage.path");

        // check for file or  metadata
        if (upload.getMetadata() == null || upload.getFile() == null || upload.getFile().length() == 0) {
            Error error = new Error(500, "File and/or metadata not present in request");
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
        }

        Metadata metadata = upload.getMetadata();

        // Check metadata for required fields
        if (metadata.getDocument_name() == null || metadata.getDocument_name().length() == 0 ||
                metadata.getDocument_type() == null || metadata.getDocument_type().length() == 0 ||
                metadata.getDocument_source() == null || metadata.getDocument_source().length() == 0) {

            Error error = new Error(400, "Metadata required fields missing or empty");
            log.warn("Metadata is missing required fields " + metadata.toString());
            return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
        }

        // Check if relation_number or account_number is filled
        if (metadata.getRelation_number() == null || metadata.getAccount_number().length() == 0) {
            Error error = new Error(400, "Metadata should at least contain an relation_number and/or account_number");
            log.warn("Metadata should at least contain an relation_number and/or account_number " + metadata.toString());
            return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
        }

        // Process metadata
        String metaName = FilenameUtils.removeExtension(metadata.getDocument_name()) + ".xml";
        String xml = MustacheTemplateEngine.instance().render("relation_document.mustache", metadata);

        byte[] filedata = xml.getBytes();
        java.nio.file.Path p = Paths.get(STORAGE_PATH, metaName);

        // Save the metadata to file
        try (OutputStream out = new BufferedOutputStream(
                Files.newOutputStream(p, CREATE, TRUNCATE_EXISTING))) {
            out.write(filedata, 0, filedata.length);
        } catch (IOException ex) {
            log.error("Error while saving metadata " + ex.getMessage(), ex);
            Error error = new Error(500, "Error while saving metadata");
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
        }

        // Try to save the uploaded file
        try {
            String docName = metadata.getDocument_name();
            String ctlName = FilenameUtils.removeExtension(metadata.getDocument_name()) + ".ctl";
            byte[] ctlData = new byte[0];
            byte[] doc = Base64.getDecoder().decode(upload.getFile().getBytes(StandardCharsets.UTF_8));

            Files.write(Paths.get(STORAGE_PATH, docName), doc);

            if (Files.exists(Paths.get(STORAGE_PATH, ctlName))) {
                log.warn("Control file " + ctlName + " already exists. It will be overwritten");
            }
            Files.write(Paths.get(STORAGE_PATH, ctlName), ctlData);

            //return metadata;
            return Response.accepted().entity(metadata).build();

        } catch (IOException e) {
            log.error("Error while writing the file " + e.getMessage(), e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e).build();
        }

    }

}


text:
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Api\ApiController;
use App\Models\Busi\StockCheckItem;

class StockCheckItemController extends ApiController
{
	//
	public function newEntity(array $attributes = [])
	{
		// TODO: Implement newEntity() method.
		return new StockCheckItem($attributes);
	}
}


text: module.exports = require('../master.json');


text:
package org.apache.jmeter.functions;

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

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.oro.text.regex.Perl5Compiler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Escape ORO meta characters
 * @since 2.9
 */
public class EscapeOroRegexpChars extends AbstractFunction {
    private static final Logger log = LoggerFactory.getLogger(EscapeOroRegexpChars.class);

    private static final List<String> desc = new ArrayList<>();

    private static final String KEY = "__escapeOroRegexpChars"; //$NON-NLS-1$

    static {
        desc.add(JMeterUtils.getResString("value_to_quote_meta")); //$NON-NLS-1$
        desc.add(JMeterUtils.getResString("function_name_paropt")); //$NON-NLS-1$
    }

    private CompoundVariable[] values;

    private static final int MAX_PARAM_COUNT = 2;

    private static final int MIN_PARAM_COUNT = 1;

    private static final int PARAM_NAME = 2;

    /**
     * No-arg constructor.
     */
    public EscapeOroRegexpChars() {
        super();
    }

    /** {@inheritDoc} */
    @Override
    public String execute(SampleResult previousResult, Sampler currentSampler)
            throws InvalidVariableException {

        String valueToEscape = values[0].execute();

        String varName = "";//$NON-NLS-1$
        if (values.length >= PARAM_NAME) {
            varName = values[PARAM_NAME - 1].execute().trim();
        }

        String escapedValue = Perl5Compiler.quotemeta(valueToEscape);

        if (!varName.isEmpty()) {
            JMeterVariables vars = getVariables();
            if (vars != null) {// Can be null if called from Config item testEnded() method
                vars.put(varName, escapedValue);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("{} name:{} value:{}", Thread.currentThread().getName(), varName, escapedValue); //$NON-NLS-1$
        }

        return escapedValue;
    }

    /** {@inheritDoc} */
    @Override
    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkParameterCount(parameters, MIN_PARAM_COUNT, MAX_PARAM_COUNT);
        values = parameters.toArray(new CompoundVariable[parameters.size()]);
    }

    /** {@inheritDoc} */
    @Override
    public String getReferenceKey() {
        return KEY;
    }

    /** {@inheritDoc} */
    @Override
    public List<String> getArgumentDesc() {
        return desc;
    }
}


text:
package edu.rice.cs.caper.floodgage.application.floodgage.synthesizer;

import java.util.List;

/**
 * A component that can synthesize programs from a given program draft.
 */
public interface Synthesizer
{
    /**
     * Synthesizes programs from the given draft. The format of draftProgram is sub-type specific.
     *
     * @param draftProgram a draft program
     * @return completed programs based on draftProgram
     * @throws SynthesizeException if synthesis can not be completed.
     */
    List<String> synthesize(String draftProgram) throws SynthesizeException;
}