text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Threading;

#if NTVS_FEATURE_INTERACTIVEWINDOW
namespace Microsoft.NodejsTools.Repl {
#else
namespace Microsoft.VisualStudio.Repl {
#endif
    internal sealed class OutputBuffer : IDisposable {
        private readonly DispatcherTimer _timer;
        private int _maxSize;
        private readonly object _lock;
        private readonly List<OutputEntry> _outputEntries = new List<OutputEntry>();
        private int _bufferLength;
        private long _lastFlush;
        private static readonly Stopwatch _stopwatch;
        private readonly ReplWindow _window;
        private const int _initialMaxSize = 1024;
        private bool _processAnsiEscapes;
        private ConsoleColor _outColor = ConsoleColor.Black, _errColor = ConsoleColor.Red;

        static OutputBuffer() {
            _stopwatch = new Stopwatch();
            _stopwatch.Start();
        }

        public OutputBuffer(ReplWindow window) {
            _maxSize = _initialMaxSize;
            _lock = new object();
            _timer = new DispatcherTimer();
            _timer.Tick += (sender, args) => Flush();
            _timer.Interval = TimeSpan.FromMilliseconds(400);
            _window = window;

            ResetColors();
        }

        public void ResetColors() {
            _outColor = ConsoleColor.Black;
            _errColor = ConsoleColor.Red;
        }

        public void Write(string text, bool isError = false) {
            bool needsFlush = false;
            lock (_lock) {
                int escape;
                if (_processAnsiEscapes && (escape = text.IndexOf('\x1b')) != -1) {
                    AppendEscapedText(text, isError, escape);
                } else {
                    AppendText(text, isError ? OutputEntryKind.StdErr : OutputEntryKind.StdOut, isError ? _errColor : _outColor);
                }

                _bufferLength += text.Length;
                needsFlush = (_bufferLength > _maxSize);
                if (!needsFlush && !_timer.IsEnabled) {
                    _timer.IsEnabled = true;
                }
            }
            if (needsFlush) {
                Flush();
            }
        }

        private void AppendEscapedText(string text, bool isError, int escape) {
            OutputEntryKind kind = isError ? OutputEntryKind.StdErr : OutputEntryKind.StdOut;
            ConsoleColor color = isError ? _errColor : _outColor;

            // http://en.wikipedia.org/wiki/ANSI_escape_code
            // process any ansi color sequences...

            int start = 0;
            List<int> codes = new List<int>();
            do {
                if (escape != start) {
                    // add unescaped text
                    AppendText(text.Substring(start, escape - start), kind, color);
                }

                // process the escape sequence
                if (escape < text.Length - 1 && text[escape + 1] == '[') {
                    // We have the Control Sequence Introducer (CSI) - ESC [

                    codes.Clear();
                    int? value = 0;

                    for (int i = escape + 2; i < text.Length; i++) { // skip esc + [
                        if (text[i] >= '0' && text[i] <= '9') {
                            // continue parsing the integer...
                            if (value == null) {
                                value = 0;
                            }
                            value = 10 * value.Value + (text[i] - '0');
                        } else if (text[i] == ';') {
                            if (value != null) {
                                codes.Add(value.Value);
                                value = null;
                            } else {
                                // CSI ; - invalid or CSI ### ;;, both invalid
                                break;
                            }
                        } else if (text[i] == 'm') {
                            if (value != null) {
                                codes.Add(value.Value);
                            }

                            // parsed a valid code
                            start = i + 1;
                            if (codes.Count == 0) {
                                // reset
                                color = isError ? ConsoleColor.Red : ConsoleColor.White;
                            } else {
                                for (int j = 0; j < codes.Count; j++) {
                                    switch (codes[j]) {
                                        case 0: color = ConsoleColor.White; break;
                                        case 1: // bright/bold
                                            color |= ConsoleColor.DarkGray;
                                            break;
                                        case 2: // faint

                                        case 3: // italic
                                        case 4: // single underline
                                            break;
                                        case 5: // blink slow
                                        case 6: // blink fast
                                            break;
                                        case 7: // negative
                                        case 8: // conceal
                                        case 9: // crossed out
                                        case 10: // primary font
                                        case 11: // 11-19, n-th alternate font
                                            break;
                                        case 21: // bright/bold off
                                            color &= ~ConsoleColor.DarkGray;
                                            break;
                                        case 22: // normal intensity
                                        case 24: // underline off
                                            break;
                                        case 25: // blink off
                                            break;
                                        case 27: // image - postive
                                        case 28: // reveal
                                        case 29: // not crossed out
                                        case 30: color = ConsoleColor.Black | (color & ConsoleColor.DarkGray); break;
                                        case 31: color = ConsoleColor.DarkRed | (color & ConsoleColor.DarkGray); break;
                                        case 32: color = ConsoleColor.DarkGreen | (color & ConsoleColor.DarkGray); break;
                                        case 33: color = ConsoleColor.DarkYellow | (color & ConsoleColor.DarkGray); break;
                                        case 34: color = ConsoleColor.DarkBlue | (color & ConsoleColor.DarkGray); break;
                                        case 35: color = ConsoleColor.DarkMagenta | (color & ConsoleColor.DarkGray); break;
                                        case 36: color = ConsoleColor.DarkCyan | (color & ConsoleColor.DarkGray); break;
                                        case 37: color = ConsoleColor.Gray | (color & ConsoleColor.DarkGray); break;
                                        case 38: // xterm 286 background color
                                        case 39: // default text color
                                            color = _outColor;
                                            break;
                                        case 40: // background colors
                                        case 41:
                                        case 42:
                                        case 43:
                                        case 44:
                                        case 45:
                                        case 46:
                                        case 47: break;
                                        case 90: color = ConsoleColor.DarkGray; break;
                                        case 91: color = ConsoleColor.Red; break;
                                        case 92: color = ConsoleColor.Green; break;
                                        case 93: color = ConsoleColor.Yellow; break;
                                        case 94: color = ConsoleColor.Blue; break;
                                        case 95: color = ConsoleColor.Magenta; break;
                                        case 96: color = ConsoleColor.Cyan; break;
                                        case 97: color = ConsoleColor.White; break;
                                    }
                                }
                            }
                            break;
                        } else {
                            // unknown char, invalid escape
                            break;
                        }
                    }

                    escape = text.IndexOf('\x1b', escape + 1);
                }// else not an escape sequence, process as text

            } while (escape != -1);
            if (start != text.Length) {
                AppendText(text.Substring(start), kind, color);
            }
        }

        private void AppendText(string text, OutputEntryKind kind, ConsoleColor color) {
            var newProps = new OutputEntryProperties(kind, color);
            if (_outputEntries.Count == 0 || _outputEntries[_outputEntries.Count - 1].Properties != newProps) {
                _outputEntries.Add(new OutputEntry(newProps));
            }
            var buffer = _outputEntries[_outputEntries.Count - 1].Buffer;
            buffer.Append(text);
        }

        public bool ProcessAnsiEscapes {
            get { return _processAnsiEscapes; }
            set { _processAnsiEscapes = value; }
        }

        /// <summary>
        /// Flushes the buffer, should always be called from the UI thread.
        /// </summary>
        public void Flush() {
            // if we're rapidly outputting grow the output buffer.
            long curTime = _stopwatch.ElapsedMilliseconds;
            if (curTime - _lastFlush < 1000) {
                if (_maxSize < 1024 * 1024) {
                    _maxSize *= 2;
                }
            }
            _lastFlush = _stopwatch.ElapsedMilliseconds;

            OutputEntry[] entries;
            lock (_lock) {
                entries = _outputEntries.ToArray();

                _outputEntries.Clear();
                _bufferLength = 0;
                _timer.IsEnabled = false;
            }

            if (entries.Length > 0) {
                _window.AppendOutput(entries);
                _window.TextView.Caret.EnsureVisible();
            }
        }

        public void Dispose() {
            _timer.IsEnabled = false;
        }

        public struct OutputEntry {
            public readonly StringBuilder Buffer;
            public readonly OutputEntryProperties Properties;

            public OutputEntry(OutputEntryProperties properties) {
                Properties = properties;
                Buffer = new StringBuilder();
            }
        }

        /// <summary>
        /// Properties for a run of text - includes destination (stdout/stderr) and color
        /// </summary>
        internal struct OutputEntryProperties {
            public readonly OutputEntryKind Kind;
            public readonly ConsoleColor Color;

            public OutputEntryProperties(OutputEntryKind kind, ConsoleColor color) {
                Kind = kind;
                Color = color;
            }

            public static bool operator ==(OutputEntryProperties l, OutputEntryProperties r) {
                return l.Kind == r.Kind && l.Color == r.Color;
            }

            public static bool operator !=(OutputEntryProperties l, OutputEntryProperties r) {
                return l.Kind != r.Kind || l.Color != r.Color;
            }

            public override bool Equals(object obj) {
                if (!(obj is OutputEntryProperties)) {
                    return false;
                }

                var other = (OutputEntryProperties)obj;
                return other == this;
            }

            public override int GetHashCode() {
                return (int)Kind  ^ ((int)Color) << 1;
            }
        }

        internal enum OutputEntryKind {
            StdOut,
            StdErr
        }
    }
}


text:
using iMotto.Adapter.Users.Requests;
using iMotto.Data;
using iMotto.Events;
using System.Threading.Tasks;

namespace iMotto.Adapter.Users.Handlers
{
    class ModifySexHandler : BaseHandler<ModifySexRequest>
    {
        private readonly IEventPublisher _eventPublisher;
        private readonly IUserRepo _userRepo;

        public ModifySexHandler(IEventPublisher eventPublisher, IUserRepo userRepo)
        {
            NeedVerifyUser = true;
            _eventPublisher = eventPublisher;
            _userRepo = userRepo;
        }

        protected override async Task<HandleResult> HandleCoreAsync(ModifySexRequest reqObj)
        {
            var rowAffected = await _userRepo.UpdateUserSexAsync(reqObj.UserId, reqObj.Sex);

            if (rowAffected > 0)
            {
                _eventPublisher.Publish(new UpdateSexEvent
                {
                    UID = reqObj.UserId,
                    Sex = reqObj.Sex
                });

                return new HandleResult {
                    State = HandleStates.Success,
                    Msg =string.Empty,
                };
            }

            return new HandleResult
            {
                State = HandleStates.NoDataFound,
                Msg = "未找到数据"
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.intercom.api;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class NotificationCollection extends TypedDataCollection<Notification> {

    public NotificationCollection() {
        type = "notification.list";
    }

    @Override
    public NotificationCollection nextPage() {
        return fetchNextPage(NotificationCollection.class);
    }

    @SuppressWarnings("EmptyMethod")
    @JsonProperty("notifications")
    @Override
    public List<Notification> getPage() {
        return super.getPage();
    }
}


text:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import com.itextpdf.text.Document;
import com.itextpdf.text.List;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.Iterator;
import com.itextpdf.text.pdf.codec.Base64.OutputStream;

public class PDFMerger {

static void mergePdfFiles(ArrayList<InputStream> inputPdfList,
        FileOutputStream outputStream) throws Exception{
    //Create document and pdfReader objects.
    Document document = new Document();
    ArrayList<PdfReader> readers =
            new ArrayList<PdfReader>();
    int totalPages = 0;

    //Create pdf Iterator object using inputPdfList.
    java.util.Iterator<InputStream> pdfIterator =
            inputPdfList.iterator();

    // Create reader list for the input pdf files.
    while (pdfIterator.hasNext()) {
            InputStream pdf = pdfIterator.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages = totalPages + pdfReader.getNumberOfPages();
    }

    // Create writer for the outputStream
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);

    //Open document.
    document.open();

    //Contain the pdf data.
    PdfContentByte pageContentByte = writer.getDirectContent();

    PdfImportedPage pdfImportedPage;
    int currentPdfReaderPage = 1;
    Iterator<PdfReader> iteratorPDFReader = readers.iterator();

    // Iterate and process the reader list.
    while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();
            //Create page and add content.
            while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
                  document.newPage();
                  pdfImportedPage = writer.getImportedPage(
                          pdfReader,currentPdfReaderPage);
                  pageContentByte.addTemplate(pdfImportedPage, 0, 0);
                  currentPdfReaderPage++;
            }
            currentPdfReaderPage = 1;
    }

    //Close document and outputStream.
    outputStream.flush();
    document.close();
    outputStream.close();

    System.out.println("Pdf files merged successfully.");
}

public static void main(String args[]){
    try {
        //Prepare input pdf file list as list of input stream.
        ArrayList<InputStream> inputPdfList = new ArrayList<InputStream>();
        inputPdfList.add(new FileInputStream("C://Java_Projects_Workspace//BREM//pdf_files//Rhino_September_2017_Summary.pdf"));
        inputPdfList.add(new FileInputStream("C://Java_Projects_Workspace//BREM//pdf_files//Rhino_September_2017_Summary.pdf"));
      //  inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf"));
      //  inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf"));

        //Prepare output stream for merged pdf file.
        FileOutputStream outputStream =
                new FileOutputStream("C://Java_Projects_Workspace//BREM//pdf_files//MergeFile_1234.pdf");

        //call method to merge pdf files.
        mergePdfFiles(inputPdfList, outputStream);
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}


text:
<?php

namespace G4\Runner\Presenter;

use G4\Constants\Format;
use G4\Constants\ContentType as ContentTypeConst;

class ContentType
{

    /**
     * @var DataTransfer
     */
    private $dataTransfer;

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

    /**
     * @var HeaderAccept
     */
    private $headerAccept;

    /**
     * @param DataTransfer $dataTransfer
     * @param HeaderAccept $headerAccept
     */
    public function __construct(DataTransfer $dataTransfer, HeaderAccept $headerAccept)
    {
        $this->dataTransfer = $dataTransfer;
        $this->headerAccept = $headerAccept;
        $this->formatFactory();
    }

    /**
     * @return string
     */
    public function getContentType()
    {
        return $this->contentTypeMap()[$this->getFormat()];
    }

    /**
     * @return \G4\Runner\Presenter\DataTransfer
     */
    public function getDataTransfer()
    {
        return $this->dataTransfer;
    }

    /**
     * @return string
     */
    public function getFormat()
    {
        return $this->format;
    }

    /**
     * @return boolean
     */
    private function isFormatValid()
    {
        return in_array($this->format, [
            Format::JSON,
            Format::TWIG,
            Format::GIF,
        ]);
    }

    /**
     * @return array
     */
    private function contentTypeMap()
    {
        return [
            Format::JSON => ContentTypeConst::JSON,
            Format::TWIG => ContentTypeConst::HTML,
            Format::GIF  => ContentTypeConst::GIF,
        ];
    }

    /**
     * @throws \Exception
     */
    private function formatFactory()
    {
        $format = $this->dataTransfer->getResponse()->getResponseObjectPart(Format::FORMAT);
        $this->format = $format === null ? $this->headerAccept->getFormat() : $format;
        if (! $this->isFormatValid()) {
            throw new \Exception('Not valid runner view format!', 600);
        }
    }
}


text:
package org.apache.drill.exec.store.pojo;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.memory.OutOfMemoryException;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.impl.OutputMutator;
import org.apache.drill.exec.record.MaterializedField.Key;
import org.apache.drill.exec.store.AbstractRecordReader;
import org.apache.drill.exec.store.pojo.Writers.BitWriter;
import org.apache.drill.exec.store.pojo.Writers.DoubleWriter;
import org.apache.drill.exec.store.pojo.Writers.EnumWriter;
import org.apache.drill.exec.store.pojo.Writers.IntWriter;
import org.apache.drill.exec.store.pojo.Writers.LongWriter;
import org.apache.drill.exec.store.pojo.Writers.NBigIntWriter;
import org.apache.drill.exec.store.pojo.Writers.NBooleanWriter;
import org.apache.drill.exec.store.pojo.Writers.NDoubleWriter;
import org.apache.drill.exec.store.pojo.Writers.NIntWriter;
import org.apache.drill.exec.store.pojo.Writers.NTimeStampWriter;
import org.apache.drill.exec.store.pojo.Writers.StringWriter;
import org.apache.drill.exec.testing.ControlsInjector;
import org.apache.drill.exec.testing.ControlsInjectorFactory;
import org.apache.drill.exec.vector.AllocationHelper;
import org.apache.drill.exec.vector.ValueVector;

import com.google.common.collect.Lists;

public class PojoRecordReader<T> extends AbstractRecordReader {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PojoRecordReader.class);
  private static final ControlsInjector injector = ControlsInjectorFactory.getInjector(PojoRecordReader.class);

  public final int forJsonIgnore = 1;

  private final Class<T> pojoClass;
  private final Iterator<T> iterator;
  private PojoWriter[] writers;
  private boolean doCurrent;
  private T currentPojo;
  private OperatorContext operatorContext;

  public PojoRecordReader(Class<T> pojoClass, Iterator<T> iterator) {
    this.pojoClass = pojoClass;
    this.iterator = iterator;
  }

  @Override
  public void setup(OperatorContext context, OutputMutator output) throws ExecutionSetupException {
    operatorContext = context;
    try {
      Field[] fields = pojoClass.getDeclaredFields();
      List<PojoWriter> writers = Lists.newArrayList();

      for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];

        if (Modifier.isStatic(f.getModifiers())) {
          continue;
        }

        Class<?> type = f.getType();
        PojoWriter w = null;
        if(type == int.class) {
          w = new IntWriter(f);
        } else if(type == Integer.class) {
          w = new NIntWriter(f);
        } else if(type == Long.class) {
          w = new NBigIntWriter(f);
        } else if(type == Boolean.class) {
          w = new NBooleanWriter(f);
        } else if(type == double.class) {
          w = new DoubleWriter(f);
        } else if(type == Double.class) {
          w = new NDoubleWriter(f);
        } else if(type.isEnum()) {
          w = new EnumWriter(f, output.getManagedBuffer());
        } else if(type == boolean.class) {
          w = new BitWriter(f);
        } else if(type == long.class) {
          w = new LongWriter(f);
        } else if(type == String.class) {
          w = new StringWriter(f, output.getManagedBuffer());
        } else if (type == Timestamp.class) {
          w = new NTimeStampWriter(f);
        } else {
          throw new ExecutionSetupException(String.format("PojoRecord reader doesn't yet support conversions from type [%s].", type));
        }
        writers.add(w);
        w.init(output);
      }

      this.writers = writers.toArray(new PojoWriter[writers.size()]);

    } catch(SchemaChangeException e) {
      throw new ExecutionSetupException("Failure while setting up schema for PojoRecordReader.", e);
    }

  }

  @Override
  public void allocate(Map<Key, ValueVector> vectorMap) throws OutOfMemoryException {
    for (ValueVector v : vectorMap.values()) {
      AllocationHelper.allocate(v, Character.MAX_VALUE, 50, 10);
    }
  }

  private void allocate() {
    for (PojoWriter writer : writers) {
      writer.allocate();
    }
  }

  private void setValueCount(int i) {
    for (PojoWriter writer : writers) {
      writer.setValueCount(i);
    }
  }

  @Override
  public int next() {
    boolean allocated = false;
    injector.injectPause(operatorContext.getExecutionControls(), "read-next", logger);
    try {
      int i =0;
      outside:
      while (doCurrent || iterator.hasNext()) {
        if (doCurrent) {
          doCurrent = false;
        } else {
          currentPojo = iterator.next();
        }

        if (!allocated) {
          allocate();
          allocated = true;
        }

        for (PojoWriter writer : writers) {
          writer.writeField(currentPojo, i);
        }
        i++;
      }

      if (i != 0 ) {
        setValueCount(i);
      }
      return i;
    } catch (IllegalArgumentException | IllegalAccessException e) {
      throw new RuntimeException("Failure while trying to use PojoRecordReader.", e);
    }
  }

  @Override
  public void cleanup() {
  }

}


text:
<?php

/**
 * @file
 * Default theme implementation to display a block.
 *
 * Available variables:
 * - $block->subject: Block title.
 * - $content: Block content.
 * - $block->module: Module that generated the block.
 * - $block->delta: An ID for the block, unique within each module.
 * - $block->region: The block region embedding the current block.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default values can be one or more of the
 *   following:
 *   - block: The current template type, i.e., "theming hook".
 *   - block-[module]: The module generating the block. For example, the user
 *     module is responsible for handling the default user navigation block. In
 *     that case the class would be 'block-user'.
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Helper variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $block_zebra: Outputs 'odd' and 'even' dependent on each block region.
 * - $zebra: Same output as $block_zebra but independent of any block region.
 * - $block_id: Counter dependent on each block region.
 * - $id: Same output as $block_id but independent of any block region.
 * - $is_front: Flags true when presented in the front page.
 * - $logged_in: Flags true when the current user is a logged-in member.
 * - $is_admin: Flags true when the current user is an administrator.
 * - $block_html_id: A valid HTML ID and guaranteed unique.
 *
 * @see template_preprocess()
 * @see template_preprocess_block()
 * @see template_process()
 *
 * @ingroup themeable
 */
 ?>

                <?php if ($block->subject): ?>

<?php print $block->subject ?>

                <?php endif; ?>

                    <?php print $content ?>

Titre publication

                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua.


text:
from vk_api.vk_api import *
import threading

class VkApiExt(VkApi):

    users = {}
    logged = ''
    def __init__(self, login=None, password=None, number=None, sec_number=None,
                 token=None, proxies=None, captcha_handler=None,
                 config_filename='vk_config.json',
                 api_version='5.44', app_id=4953880, scope=33554431,
                 client_secret=None):
        super().__init__(login, password, number, sec_number,
                 token, proxies, captcha_handler,
                 config_filename,
                 api_version, app_id, scope,
                 client_secret)
        self.methodLock = threading.Lock()
        self.id = self.method('users.get')[0]['id']
        self.init_users()
        self.guid = 0

    def method(self, method, values=None, captcha_sid=None, captcha_key=None):
        self.methodLock.acquire()
        try:
            val = super().method(method, values, captcha_sid, captcha_key)
        finally:
            self.methodLock.release()
        return val

    def sendMessage(self, values, captcha_sid=None, captcha_key=None):
        # values['guid'] = self.guid
        self.guid+=1
        return self.method('messages.send', values=values, captcha_sid=captcha_sid, captcha_key=captcha_key)

    def init_users(self):
        r = self.method('friends.get')
        ids = r['items']
        names = self.method('users.get', {'user_ids' : ",".join(map(str, ids))})
        for user in names:
            self.users[int(user['id'])] = user

    def get_user(self, id):
        id = int(id)
        if id in self.users:
            return self.users[id]
        else:
            user = self.method('users.get', {'user_ids' : id})
            if user:
                self.users[id] = user[0]
                return user[0]


text:
package com.snkinard.coding;

import org.testng.AssertJUnit;
import org.testng.annotations.Test;

public class ReversedWordsAreTheseTest {

    @Test
    public void testReverseWords()
            throws Exception {
        StringBuffer input = new StringBuffer("I am Sam");
        AssertJUnit.assertEquals("Expected output to be reversed.", ReversedWordsAreThese.reverseWords(input), "Sam am I");
    }

    @Test
    public void testReverseStringBuffer() {
        StringBuffer input = new StringBuffer("maS ma I");
        ReversedWordsAreThese.reverseStringBuffer(input, 0, 2);
        AssertJUnit.assertEquals("Broke ass shit!",  "Sam ma I", input.toString());
        ReversedWordsAreThese.reverseStringBuffer(input, 4, 5);
        AssertJUnit.assertEquals("Broke ass shit!",  "Sam am I", input.toString());
        ReversedWordsAreThese.reverseStringBuffer(input, 7, 7);
        AssertJUnit.assertEquals("Broke ass shit!",  "Sam am I", input.toString());
    }
}


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class YieldIntegrationType
{
    const UNKNOWN = 'UNKNOWN';
    const CUSTOM_EVENT = 'CUSTOM_EVENT';
    const SDK = 'SDK';
    const OPEN_BIDDING = 'OPEN_BIDDING';
    const NETWORK_BIDDING = 'NETWORK_BIDDING';

}


text:
from botocore import xform_name
from botocore.compat import OrderedDict
from botocore.docs.utils import DocumentedShape
from botocore.utils import get_service_module_name
from botocore.docs.method import document_model_driven_method

class WaiterDocumenter(object):
    def __init__(self, client, service_waiter_model):
        self._client = client
        self._service_name = self._client.meta.service_model.service_name
        self._service_waiter_model = service_waiter_model

    def document_waiters(self, section):
        """Documents the various waiters for a service.

        :param section: The section to write to.
        """
        section.style.h2('Waiters')
        section.style.new_line()
        section.writeln('The available waiters are:')
        for waiter_name in self._service_waiter_model.waiter_names:
            section.style.li(
                ':py:class:`%s.Waiter.%s`' % (
                    self._client.__class__.__name__, waiter_name))
            self._add_single_waiter(section, waiter_name)

    def _add_single_waiter(self, section, waiter_name):
        section = section.add_new_section(waiter_name)
        section.style.start_sphinx_py_class(
            class_name='%s.Waiter.%s' % (
                self._client.__class__.__name__, waiter_name))

        # Add example on how to instantiate waiter.
        section.style.start_codeblock()
        section.style.new_line()
        section.write(
            'waiter = client.get_waiter(\'%s\')' % xform_name(waiter_name)
        )
        section.style.end_codeblock()

        # Add information on the wait() method
        section.style.new_line()
        document_wait_method(
            section=section,
            waiter_name=waiter_name,
            event_emitter=self._client.meta.events,
            service_model=self._client.meta.service_model,
            service_waiter_model=self._service_waiter_model
        )

def document_wait_method(section, waiter_name, event_emitter,
                         service_model, service_waiter_model,
                         include_signature=True):
    """Documents a the wait method of a waiter

    :param section: The section to write to

    :param waiter_name: The name of the waiter

    :param event_emitter: The event emitter to use to emit events

    :param service_model: The service model

    :param service_waiter_model: The waiter model associated to the service

    :param include_signature: Whether or not to include the signature.
        It is useful for generating docstrings.
    """
    waiter_model = service_waiter_model.get_waiter(waiter_name)
    operation_model = service_model.operation_model(
        waiter_model.operation)

    waiter_config_members = OrderedDict()

    waiter_config_members['Delay'] = DocumentedShape(
        name='Delay', type_name='integer',
        documentation=(
            '
The amount of time in seconds to wait between '
            'attempts. Default: {0}
'.format(waiter_model.delay)))

    waiter_config_members['MaxAttempts'] = DocumentedShape(
        name='MaxAttempts', type_name='integer',
        documentation=(
            '
The maximum number of attempts to be made. '
            'Default: {0}
'.format(waiter_model.max_attempts)))

    botocore_waiter_params = [
        DocumentedShape(
            name='WaiterConfig', type_name='structure',
            documentation=(
                '
A dictionary that provides parameters to control '
                'waiting behavior.
'),
            members=waiter_config_members)
    ]

    wait_description = (
        'Polls :py:meth:`{0}.Client.{1}` every {2} '
        'seconds until a successful state is reached. An error is '
        'returned after {3} failed checks.'.format(
            get_service_module_name(service_model),
            xform_name(waiter_model.operation),
            waiter_model.delay, waiter_model.max_attempts)
    )

    document_model_driven_method(
        section, 'wait', operation_model,
        event_emitter=event_emitter,
        method_description=wait_description,
        example_prefix='waiter.wait',
        include_input=botocore_waiter_params,
        document_output=False,
        include_signature=include_signature
    )


text:
这篇文章主要用于记录自己在开发中遇到的应用性能问题。

---

# 1.内存泄露

**避免内存泄露须谨记**

-  1.不要让生命周期长于Activity的对象持有到Activity的引用

- 2.尽量使用Application的Context而不是Activity的Context

-  3.尽量不要在Activity中使用非静态内部类,因为非静态内部类会隐式持有外部类实例的引用。如果使用静态内部类,将外部实例引用作为弱引用持有。

- 4.垃圾回收不能解决内存泄露,了解Android中垃圾回收机制

---

## 1.1内存泄露检测工具
[leakcanary内存泄露检测库](https://github.com/square/leakcanary)

这个使用就不说了,可以见github。

---
## 1.2常见的内存泄露

### 1.2.1Context导致的内存泄露
[避免Android中Context引起的内存泄露](http://droidyue.com/blog/2015/04/12/avoid-memory-leaks-on-context-in-android/)

#### 1.2.1.1.单例模式导致Context的内存泄露
有时候我们会创建一个静态类,比如说AppManager、XXXManager。这些静态类可能还是以单例的形式存在。而这些静态类需要做一个关于UI的处理,所以传递了一个Context进来,代码如下:

```

public class ToastManager {
    private Context mContext;
    ToastManager(Context context){
        mContext = context;
    }

    private static ToastManager mManager = null;

    public void showToast(String str){
        if(mContext==null){
            return;
        }
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

    public static ToastManager getInstance(Context context){
        if(mManager==null){
            synchronized (ToastManager.class){
                if(mManager==null){
                    mManager = new ToastManager(context);
                }
            }
        }
        return mManager;
    }
}

```

而在使用时是这样写的:

```
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        ToastManager instance = ToastManager.getInstance(MainActivity.this);
    }
}
```
这个时候代码也会发生内存泄露。因为静态实例比Activity生命周期长,你在使用静态类时将Activity作为context参数传了进来,即使Activity被关掉,但是静态实例中还保有对它的应用,所以会导致Activity没法被及时回收,造成内存泄露。

解决方案:在传Context上下文参数时,尽量传跟Application应用相同生命周期的Context。比如getApplicationContext(),因为静态实例的生命周期跟应用Application一致。

```

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ToastManager instance = ToastManager.getInstance(getApplicationContext());
    }
}

```

---

### 1.2.2内部类导致内存泄露
内部类实例会隐式的持有外部类的引用。

比如说在Activity中去创建一个内部类实例,然后在内部类实例中去执行一些需要耗时间的任务。任务在执行过程中,将Activity关掉,这个时候Activity对象是不会被释放的,因为那个内部类还持有着对Activity的引用。但是Activity此时已经是个没用的Activity了,所有这时,内存泄露就出现了。

隐式持有外部类的说明:内部类可以直接去调用外部类的方法,如果没有持有外部类的引用,内部类是没办法去调用外部类的属性和方法的,但是内部类又没有明显的去指定和声明引用,所以称之为隐式引用。

#### Thread线程

在Activity中创建一个内部类去继承Thread,然后让该Thread执行一些后台任务,未执行完时,关闭Activity,此时会内存泄露。核心代码如下:

```

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startThread();
            }
        });
    }

    private void startThread() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 20; i++) {
                    SystemClock.sleep(1000);
                }
            }
        };
        thread.start();
    }

}
```

当点击页面按钮执行startThread()后,再按下back键关闭Activity,几秒后LeakCanary就会提示内存泄露了。

为了避免此种Thread相关内存泄露,只需要避免这个内部类去隐式引用外部类Activity即可。

解决方案:让这个内部类声明为静态类。代码如下:

```
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...与先前相比未做变化,不再描述
    }

    private void startThread() {
        Thread thread = new MyStaticThread();
        thread.start();
    }

    private static class MyStaticThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 200; i++) {
                SystemClock.sleep(1000);
            }
        }
    }
}
```

这样声明为静态类后,该内部类将不会再去隐式持有外部类的应用。

如果像这样的循环操作,为了效率和优化,建议通过申明一个boolean类型的标志位来控制后台任务。比如在外部类Activity的onDestory退出方法中,将boolean值进行修改,使后台任务退出循环。代码如下:

```

public class MainActivity extends AppCompatActivity {

    ...
    //Activity页面是否已经destroy
    private static boolean isDestroy = false;

    private static class MyStaticThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                if(!isDestroy){
                    SystemClock.sleep(1000);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroy = true;
    }
}
```

因为申明为了静态内部类,该内部类不再持有外部类Activity的引用,所以此时不能再去使用外部类中的方法、变量。除非外部类的那些方法、变量是静态的。

Q:在防止内存泄露的前提下,如果一定要去使用那些外部类中非静态的方法、变量,该怎么做?

A:通过使用弱引用或者软引用的方式,来引用外部类Activity。代码如下:

```

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    }

    private void startThread() {
        Thread thread = new MyStaticThread(MainActivity.this);
        thread.start();
    }

    private  boolean isDestroy = false;//Activity页面是否已经destroy

    private static class MyStaticThread extends Thread {

        private WeakReference<MainActivity> softReference = null;

        MyStaticThread(MainActivity mainActivity){
            this.softReference = new WeakReference<MainActivity>(mainActivity);
        }

        @Override
        public void run() {
            //能够isDestroy变量是非静态的,它属于MainActivity,我们只要拿到了MainActivity对象,就能拿到isDestroy
            MainActivity mainActivity = softReference.get();
            for (int i = 0; i < 200; i++) {
                //使用前最好对MainActivity对象做非空判断,如果它已经被回收,就不再执行后台任务
                if(mainActivity!=null&&!mainActivity.isDestroy){
                    SystemClock.sleep(1000);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroy = true;
    }
}
```

---
### 1.2.3Handler引起的内存泄露

下面看一个Handler内存泄露的例子:
```
/**
 * handler导致的内存泄露
 */
public class HandlerTestActivity extends AppCompatActivity {
    private Button bt1;
    private TextView tv1;
    private static final String TAG = "HandlerTestActvitiy";
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tv1.setText(String.valueOf(msg.arg1));
                    Log.d(TAG, "handleMessage.message:" + msg.arg1);
                    break;
                case 2:
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_test);
        bt1 = (Button) findViewById(R.id.bt1);
        tv1 = (TextView) findViewById(R.id.tv1);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                finish();
            }
        });
        Message message = new Message();
        message.what = 1;
        message.arg1 = 1;
        //        mHandler.sendMessage(message);平常很多人这样写貌似没出现内存泄露,由于时间太短了,快速点击就会出现,所以这种写法是有问题的
        mHandler.sendMessageDelayed(message, 30000);
    }
}
```
![image](http://note.youdao.com/yws/api/personal/file/9BBA10D5334D427FA59FEEBCB7BA74B9?method=download&shareKey=a151711c028dac98af0988c0679a5df6)

Handler通过发送Message与主线程交互是应用开发中非常常见的使用场景之一,Message发送后存在MessageQueue中,有些Message也不是马上就能被处理(如上延时30s),在message中存在一个target,它是handler的一个引用,Message在Queue中存在的时间过长,就会导致handler无法被回收,如果handler是非静态的,则会导致Activity或者Service不能被回收,从而内存泄露。

那么我们要如何写呢?

下面是标准的写法(可作为模板)

```
public class HandlerTestRightActivity extends Activity {
    private Button bt1;
    private TextView tv1;
    private static final String TAG = "HandlerTestRight";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_test);
        bt1 = (Button) findViewById(R.id.bt1);
        tv1 = (TextView) findViewById(R.id.tv1);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                finish();
            }
        });
        Message message = new Message();
        message.what = 1;
        message.arg1 = 1;
        mHandler.sendMessageDelayed(message, 30000);
    }

    final Handler mHandler = new myHandler(this);

    static class myHandler extends Handler {
        WeakReference<HandlerTestRightActivity> handlerTestRightActivityWeakReference;

        public myHandler(HandlerTestRightActivity handlerTestRightActivity) {
            this.handlerTestRightActivityWeakReference = new WeakReference<>(handlerTestRightActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            HandlerTestRightActivity activity = handlerTestRightActivityWeakReference.get();
            switch (msg.what) {
                case 1:
                    if (activity != null) {
                        Log.d(TAG, "handleMessage.mHandler");
                        activity.tv1.setText("mHandler");
                    }
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
    }

}
```

[Android中Handler引起的内存泄露-技术小黑屋](http://droidyue.com/blog/2014/12/28/in-android-handler-classes-should-be-static-or-leaks-might-occur/)

---

### 1.2.4静态变量导致的内存泄露

```
public class MainActivity extends AppCompatActivity {
    private static Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
//        context = this.getApplicationContext();//正确用法
    }
}
```
![image](http://note.youdao.com/yws/api/personal/file/CC50EA7E07BE47CB842600E708527479?method=download&shareKey=defd2aaf03bcef9182c19023fe3ee621)

从上图可以看到 MainActivity中静态的context导致MainActivity实例内存泄露
### 1.2.5属性动画导致的内存泄漏
从Android3.0开始,Google提供了属性动画,属性动画中有一类无限循环的动画,如果在Activity中播放此类动画并且在onDestroy()方法中没有停止该动画,那么动画会一直循环下去,尽管在界面上已经无法看不到动画了,但这个时候Activity的View会被动画持有,而View又持有Activity,最终Activity无法释放。下面的动画是无限循环的,会泄露当前的Activity。

```
public class HomeActivity extends Activity {
    Button btn_home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_home);
        btn_home = (Button) findViewById(R.id.btn_home);
        ObjectAnimator animator = ObjectAnimator.ofFloat(btn_home, "ratation", 0, 360).setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.start();
    }
}
```

解决方案:
    在当前Activity的onDestroy()方法中取消动画:animator.cancel()。

```
public class HomeActivity extends Activity {
    private Button btn_home;
    private ObjectAnimator animator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_home);
        btn_home = (Button) findViewById(R.id.btn_home);

        animator = ObjectAnimator.ofFloat(btn_home, "ratation", 0, 360).setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        animator.cancel();
    }
}
```
### 1.2.6.InputMethodManager造成的内存泄漏问题及解决方法
这个网上已经有解决方案了,反射置空,解决了。
[InputMethodManager造成的内存泄漏问题及解决方法](http://blog.csdn.net/sodino/article/details/32188809)
---

### 1.2.7 线程导致的内存泄露

```
//这里只是为了演示
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("hxk", "onCreate!");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("hxk", "thread");
            }
        }).start();
    }
```
在Monitor Memory中可以很清晰的看到内存大幅度波动。

在处理这个问题时,还看到我们系统改出来的一个bug,activity退出了,线程不执行了。原生的线程的run方法会继续执行的。如果需要在activity退出时停止线程,可以加关键字:

# 2.性能优化

---

## 2.1性能优化工具

[JakeWharthon大神的方法执行时间长度库](https://github.com/JakeWharton/hugo)

使用方式见github
## 2.2 性能优化典范
避免创建不必要对象,能用局部变量的不要用全局变量

避免使用float类型

使用增强的For循环

[胡凯-性能优化](http://hukai.me/android-training-course-in-chinese/performance/performance-tips.html)

---
# 3.高质量代码
如何写出高质量代码,多看优秀代码,多思考。
## 3.1高质量代码

---

挺好的文章:

[掘金官方性能优化文章](http://www.jianshu.com/p/e6707310c915)


text:
module Strive.Options.Uploads
  ( UploadActivityOptions(..)
  ) where

import Data.Default (Default, def)
import Network.HTTP.Types (QueryLike, toQuery)
import Strive.Enums (ActivityType)

-- | 'Strive.Actions.uploadActivity'
data UploadActivityOptions = UploadActivityOptions
  { uploadActivityOptions_activityType :: Maybe ActivityType
  , uploadActivityOptions_name :: Maybe String
  , uploadActivityOptions_description :: Maybe String
  , uploadActivityOptions_private :: Bool
  , uploadActivityOptions_trainer :: Bool
  , uploadActivityOptions_externalId :: Maybe String
  }
  deriving Show

instance Default UploadActivityOptions where
  def = UploadActivityOptions
    { uploadActivityOptions_activityType = Nothing
    , uploadActivityOptions_name = Nothing
    , uploadActivityOptions_description = Nothing
    , uploadActivityOptions_private = False
    , uploadActivityOptions_trainer = False
    , uploadActivityOptions_externalId = Nothing
    }

instance QueryLike UploadActivityOptions where
  toQuery options = toQuery
    [ ("activity_type", fmap show (uploadActivityOptions_activityType options))
    , ("name", uploadActivityOptions_name options)
    , ("description", uploadActivityOptions_description options)
    , ( "private"
      , Just (show (fromEnum (uploadActivityOptions_private options)))
      )
    , ( "trainer"
      , Just (show (fromEnum (uploadActivityOptions_trainer options)))
      )
    , ("external_id", uploadActivityOptions_externalId options)
    ]


text:
"""
Django settings for cbe project.

Generated by 'django-admin startproject' using Django 1.8.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!vv05q%k$8nhc6t&*2u4yxd_wplret8@gajcng%q@x4@fmhvuq'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*',]

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'drf_yasg',
    'django_nose',
    'rest_framework',
    'gm2m',
    'cbe.location',
    'cbe.party',
    'cbe.business_interaction',
    'cbe.customer',
    'cbe.credit',
    'cbe.physical_object',
    'cbe.supplier_partner',
    'cbe.human_resources',
    'cbe.resource',
    'cbe.trouble',
    'cbe.information_technology',
    'cbe.project',
    'cbe.accounts_receivable',
)

#python manage.py makemigrations location party customer credit physical_object supplier_partner human_resources resource trouble information_technology project accounts_receivable

MIDDLEWARE = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'cbe.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'cbe.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
}

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissions'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'drf_nest.api.BrowsableAPIRendererWithoutForms',
        'drf_nest.api.PaginatedCSVRenderer',
    ),
}

MQ_FRAMEWORK = {
    'TYPE': 'stdout',
    'HOST': 'None',
    'USER': 'None',
    'PASSWORD': 'None',
    'EXCHANGE_PREFIX': 'notify.',
    'HTTP_REST_CONTEXT': {
        'SERVER_NAME': '127.0.0.1',
        'SERVER_PORT': 8000,
        'SERVER_PROTOCOL': 'http',
    }
}

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
    # '--with-coverage',
    # '--cover-package=cbe.location,cbe.party,cbe.business_interaction,cbe.customer,cbe.trouble',
]

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
USE_I18N = True

USE_L10N = True

#USE_TZ = True
USE_TZ = False

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

# LimitDepthMixin serializer setting
DEPTH_MAX = 2

# Try to use a local settings file if available
try:
    from cbe.local_settings import *
except ImportError:
    pass


text:
FROM centos/systemd
MAINTAINER dev@trafficcontrol.apache.org

RUN yum install -y \
  https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm \
  initscripts epel-release perl-Crypt-ScryptKDF perl cpanminus perl-Test-CPAN-Meta perl-DBIx-Connector

RUN cpanm Carton

# Override RPM arg to use a different one using --build-arg RPM=...  Can be local file or http://...
ARG RPM=traffic_ops.rpm
ADD traffic_ops/$RPM /
RUN yum install -y /$(basename $RPM)

# once installed, remove rpm to lower image size
RUN rm /$(basename $RPM)

RUN POSTGRES_HOME=/usr/pgsql-9.6 cd /opt/traffic_ops/app && carton

RUN export PERL5LIB=/opt/traffic_ops/app/local/lib/perl5/:/opt/traffic_ops/install/lib/ \
	&& export TERM=xterm \
	&& export USER=root

# fixes an 'Invalid Argument' bug; TODO diagnose    , fix, & remove
RUN cp /opt/traffic_ops/app/bin/traffic_ops_golang{,.new} && mv /opt/traffic_ops/app/bin/traffic_ops_golang{.new,}

EXPOSE 443
WORKDIR /opt/traffic_ops/app
ENV MOJO_MODE production
ADD traffic_ops/profile.origin.traffic_ops /
ADD traffic_ops/run.sh /
CMD /run.sh


text:
package org.archive.crawler.postprocessor;

import javax.management.AttributeNotFoundException;

import org.archive.crawler.datamodel.CrawlURI;
import org.archive.crawler.settings.SimpleType;
import org.archive.util.TextUtils;

/**
 * A WaitEvaluator that compares the CrawlURIs content type to a configurable
 * regular expression. If it matches, then the wait evaluation is performed.
 * Otherwise the processor passes on the CrawlURI, doing nothing.
 *
 * @author Kristinn Sigurdsson
 *
 * @see org.archive.crawler.postprocessor.WaitEvaluator
 */
public class ContentBasedWaitEvaluator extends WaitEvaluator {

    private static final long serialVersionUID = 1623347208782997347L;

    /** The regular expression that we limit this evaluator to. */
    public final static String ATTR_CONTENT_REGEXPR =
        "content-regular-expression";
    protected final static String DEFAULT_CONTENT_REGEXPR = "^.*$"; //Everything

    /**
     * Constructor
     *
     * @param name The name of the module
     */
    public ContentBasedWaitEvaluator(String name) {
        this(name,"Evaluates how long to wait before fetching a URI again. " +
                "Only handles CrawlURIs whose content type matches the " +
                "regular expression set. " +
                "Typically, this processor should be in the post processing " +
                "chain. It will pass if another wait evaluator has already " +
                "processed the CrawlURI.", DEFAULT_CONTENT_REGEXPR,
                DEFAULT_INITIAL_WAIT_INTERVAL,
                DEFAULT_MAX_WAIT_INTERVAL,
                DEFAULT_MIN_WAIT_INTERVAL,
                DEFAULT_UNCHANGED_FACTOR,
                DEFAULT_CHANGED_FACTOR);
    }

    /**
     * Constructor
     *
     * @param name The name of the module
     * @param description Description of the module
     * @param default_inital_wait_interval The default value for initial wait
     *           time
     * @param default_max_wait_interval The maximum value for wait time
     * @param default_min_wait_interval The minimum value for wait time
     * @param default_unchanged_factor The factor for changing wait times of
     *           unchanged documents (will be multiplied by this value)
     * @param default_changed_factor The factor for changing wait times of
     *           changed documents (will be divided by this value)
     */
    public ContentBasedWaitEvaluator(String name, String description,
            String defaultRegExpr,
            Long default_inital_wait_interval,
            Long default_max_wait_interval,
            Long default_min_wait_interval,
            Double default_unchanged_factor,
            Double default_changed_factor){
        super(name,description,
                default_inital_wait_interval,
                default_max_wait_interval,
                default_min_wait_interval,
                default_unchanged_factor,
                default_changed_factor);

        addElementToDefinition(new SimpleType(ATTR_CONTENT_REGEXPR,
                "Only URIs whose content type matches this regular " +
                "expression will be evaluated.",
                defaultRegExpr));

    }

    protected void innerProcess(CrawlURI curi) throws InterruptedException {
        // Check if content type is available and if it matches the reg.expr.
        String content_type = curi.getContentType();
        if(content_type==null){
            // No content type, exit
            return;
        }
        String regexpr;
        try {
            regexpr = (String)getAttribute(curi,ATTR_CONTENT_REGEXPR);
        } catch (AttributeNotFoundException e) {
            logger.warning("Regular expression for content type not found");
            return;
        }

        if(TextUtils.matches(regexpr, content_type) == false){
            // Content type does not match reg.expr. Exit
            return;
        }
        // Ok, it matches, invoke parent method.

        super.innerProcess(curi);
    }
}


text:
Alloy.Globals.extendsBaseViewController($, arguments[0]);

$.moneyIncomeDetailsTable.UIInit($, $.getCurrentWindow());

var selectedIncome = $.$attrs.selectedIncome;

$.makeContextMenu = function(e, isSelectMode, sourceModel) {
	var menuSection = Ti.UI.createTableViewSection();
	menuSection.add($.createContextMenuItem("新增收入明细", function() {
		Alloy.Globals.openWindow("money/moneyIncomeDetailForm", {
			selectedIncome : selectedIncome,
			closeWithoutSave : $.getCurrentWindow().$attrs.closeWithoutSave
		});
	}, !selectedIncome.canAddNew()));
	return menuSection;
};

// $.titleBar.bindXTable($.moneyIncomeDetailsTable);

var collection = selectedIncome.xGet("moneyIncomeDetails");
$.moneyIncomeDetailsTable.addCollection(collection);
$.moneyIncomeDetailsTable.autoHideFooter($.footerBar);

$.onWindowOpenDo(function() {
	if (!selectedIncome.canAddNew()) {
		$.footerBar.addIncomeDetail.setEnabled(false);
	}
});

function onFooterbarTap(e) {
	if (e.source.id === "addIncomeDetail") {
		Alloy.Globals.openWindow("money/moneyIncomeDetailForm", {
			selectedIncome : selectedIncome,
			closeWithoutSave : $.getCurrentWindow().$attrs.closeWithoutSave
		});
	}
}
$.titleBar.UIInit($, $.getCurrentWindow());


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<!--
  ~ Copyright 2013-2015 The GDG Frisbee Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ 	http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<resources>
  <string name="news">Hírek</string>
  <string name="drawer_open">Fiók megnyitása</string>
  <string name="drawer_close">Fiók bezárása</string>
  <string name="info">Információ</string>
  <string name="events">Események</string>
  <string name="add_to_calendar">Hozzáadás a naptárhoz</string>
  <string name="share_with_googleplus">Megosztás a Google+-al</string>
  <string name="no_scheduled_events">Nincs esemény beütemezve\naz elkövetkezendő 30 napra</string>
  <string name="organizers">Szervezők</string>
  <string name="resources">Linkek</string>
  <string name="fetch_events_failed">Nem sikerült letölteni a közelgő eseményeket</string>
  <string name="fetch_chapters_failed">Nem sikerült beolvasni a fejezet listát</string>
  <string name="bogus_organizer">Nem sikerült értelmezni szervező azonosítót: %1$s</string>
  <string name="cached_content">Jelenleg nincs net kapcsolat. Íme néhány elmentett tartalom.</string>
  <string name="offline_alert">Jelenleg nincs net kapcsolat.</string>
  <string name="welcome">Üdvözlet</string>
  <string name="welcome_sign_in">Üdvözlet! %s</string>
  <string name="choose_home_gdg">Válaszd ki az otthoni GDG-det</string>
  <string name="signin_with_google">Bejelentkezés Google-lel</string>
  <string name="confirm">Jóváhagy</string>
  <string name="signin_description">A GDG Alkalmazás Google+-t és egyéb Google szolgáltatásokat vesz igénybe. Ezért e funkció használatához be kell hogy jelentkezzél a Google-lel.</string>
  <string name="or">vagy</string>
  <string name="skip">Bejelentkezés átugrása</string>
  <string name="youtube_init_failed">Nem sikerült inicializálni a YouTube-lejátszót.</string>
  <string name="settings">Beállítások</string>
  <string name="about">Az alkalmazásról</string>
  <plurals name="seconds_ago">
    <item quantity="one">ebben a pillanatban</item>
    <item quantity="other">%d másodperce</item>
  </plurals>
  <plurals name="minutes_ago">
    <item quantity="one">1 perce</item>
    <item quantity="other">%d perce</item>
  </plurals>
  <plurals name="hours_ago">
    <item quantity="one">1 órája</item>
    <item quantity="other">%d órája</item>
  </plurals>
  <plurals name="days_ago">
    <item quantity="one">1 napja</item>
    <item quantity="other">%d napja</item>
  </plurals>
  <string name="contributors">A GDG alkalmazás közösségi erőfeszítés eredménye és nyílt forrású. A következő emberek járultak hozzá az alkalmazáshoz:</string>
  <string name="get_involved">Kapcsolódj be Te is!</string>
  <string name="get_involved_text">A GDG alkalmazás közösségi erőfeszítés eredménye és nyílt forrású. Bárki részt vehet benne és hozzáadhat az alkalmazáshoz.\n\nEhhez navigálj el a GitHub oldalunkra és tekintsd meg a forráskódot.\n\nhttps://github.com/gdg-x</string>
  <string name="about_license">© 2013 The GDG Frisbee Project\nMinden jog fenntartva.\n\nLicenszelve\naz Apache 2.0 licenc alapján</string>
  <string name="past_event">KORÁBBI</string>
  <string name="upcoming_widget">GDG - közelgő esemény</string>
  <string name="global">Globális</string>
  <string name="pulse">GDG Pulse</string>
  <string name="pulse_events">Események</string>
  <string name="pulse_attendees">Résztvevők</string>
  <string name="pulse_circlers">Fejezet csoportok</string>
  <string name="home_gdg">Otthoni GDG</string>
  <string name="home_gdg_with_city">Otthoni GDG: %1$s</string>
  <string name="home_gdg_summary">Válaszd ki az elsődleges GDG-det</string>
  <string name="remove_trailing_spaces">Távolítsd el a space-eket a szöveg végéről</string>
  <string name="analytics">Analízis</string>
  <string name="analytics_summary_on">Az alkalmazás jelenleg névtelen használat adatokat továbbít, amelyek lehetővé teszik számunkra, hogy javítsunk az alkalmazáson</string>
  <string name="analytics_summary_off">Az alkalmazás jelenleg nem továbbít semmilyen névtelen használati adatot</string>
  <string name="gcm">Google Felhő Értesítések</string>
  <string name="gcm_summary_on">Az alkalmazás jelenleg GDG felhő értesítést fogad és dolgoz fel</string>
  <string name="gcm_summary_off">Az alkalmazás jelenleg nem fogad GDG felhő értesítést</string>
  <string name="google_signed_in">Bejelentkeztél a Google+-al</string>
  <string name="google_signed_in_on">Jelenleg be vagy jelentkezve Google+-al</string>
  <string name="google_signed_in_off">Nem vagy bejelentkezve</string>
  <string name="done">Kész</string>
  <string name="allow_analytics">Kérjük tedd lehetővé, hogy névtelen használati adatokat gyűjthessünk, amelyek segíthetnek, hogy fejlesszük az alkalmazást</string>
  <string name="enable_gcm">Engedélyezi a GDG felhő értesítéseket (értesítések az új eseményekről)</string>
  <string name="step3_text">Még egy dolog mielőtt elkezdjük…</string>
  <string name="invite_friends">Barátok meghívása</string>
  <string name="join_me">Csatlakozz hozzám ezen az eseményen!</string>
  <string name="name_not_known">Neve ismeretlen</string>
  <string name="originally_shared">eredetileg megosztotta:</string>
  <string name="server_error">Hiba történt. Kérjük, próbáld meg újra.</string>
  <string name="search_hint">GDG fejezetek keresése</string>
  <string name="dashclock_description">Jelenítsen meg információt az otthoni GDG-ben közelgő eseményekről</string>
  <string name="order_by_date">Dátum szerinti rendezés</string>
  <string name="order_by_distance">Távolság szerinti rendezés</string>
  <string name="gcm_event_ticker">Az otthoni GDG-d új eseményt ütemezett be.</string>
  <string name="ioextended_description">A Kiterjesztett Google I/O a helyi csoportoddal a Google-konferenciához való távolról csatlakozásról szól.</string>
  <string name="gcpnext_description">A GCP NEXT kiterjesztett események összehozzák a helyi fejlesztői közösséget, hogy együtt előadásokat, részletes termék bemutatókat és színfalak mögött interjúkat nézhessenek. Minden fő előadás és technikai előadás on-line is el lesz elérhető időben eltolt megtekintésre. Az esemény ezen kívül is kínál egyedi tevékenységeket a fejlesztőknek, mint például felhős kód laboratóriumokat vagy hackathon-okat.</string>
  <string name="devfest_description">A GDG DevFest-ek nagy, közösségi szervezésű események, amik több témakörben ajánlanak előadásokat, egész napos hackathon-okat, kód laboratóriumokat és még sok egyebet.\n\nMinden GDG DevFest-et a helyi fejlesztői közösség ihleti és annak egyedi igényeihez igazodik, Bár nincs két egyforma DevFest, minden GDG DevFest a lényegét tekintve azon közös hit által inspirált, hogy a fejlesztők összeröffenhetnek, hogy öteletet cseréljenek.</string>
  <string name="studyjams_description">Google Fejlesztő Tanulmányi szakkörök ingyenes, globális, közösségileg szervezett tanulmányi szakkörök. Az első Tanulmány szakkör sorozat a Udacity-vel együttműködve valósul meg, és az Android Alapjai tantervet követi. A Google Fejlesztői Csoport segítők vezetik majd a szakköröket, melyek 8-9 hetente üléseznek.</string>
  <string name="wtm_description">A Women Techmakers a Google globális programja és a márkája a nők technológiai részvételéért. 2012-ben az akkori Google[x] VP Megan Smith által alapította, ma pedig a Women Techmakers-t a Women in Technology aktivista Natalie Villalobos és a Google egy globális csapata vezeti, akik a elkötelezettek a nők segítésében a technológia terén a nagyobb láthatóság, a közösség és a más erőforrások révén.\n\nMinden csúcstalálkozónk és összejövetelünk a nők helyi technológiai közösségéről gondoskodik. Csúcstalálkozók és a világ minden táján összejövetelek többek között kódoló gyakorlatokat, inspiráló előadókat, és a kapcsolati lehetőségeket biztosítanak.</string>
  <string name="media_route_menu_title">Előadás átirányitása</string>
  <string name="navigate_to">Eseményhez navigálás</string>
  <string name="gde">Google Developer Experts</string>
  <string name="fetch_gde_failed">Nem sikerült a GDE könyvtár letöltése…</string>
  <string name="gde_who_title">Kik azok a Google Fejlesztői Szakértők?</string>
  <string name="gde_who_desc">A Google Fejlesztői Szakértők (GDE-k) olyan szakemberek, akik egy vagy több Google fejlesztői technológiában profik. A GDE program felismeri ezen rocksztárok példaértékű munkáját, világszerte felkérve őket, hogy legyenek a növekvő GDE közösség tagjai. A GDE-k guruk, mesterek, mentorok és barátok, csakúgy mint te.\n\nA Google Fejlesztő Szakértők helyi és globális eseményeken beszélnek, erős online jelenlétük van és a kiváló a technikai hátterük a maguk területén. Ezek a független fejlesztők az élet tapasztalataikat és a tudásukat adják át a Google technológiákkal kapcsolatban világszerte a fejlesztői közösségnek.</string>
  <string name="gde_what_title">Milyen tevékenységeket végeznek a GDE-k?</string>
  <string name="gde_what_desc">A GDE-ek forrás kódokat írnak, alkalmazásokat készítenek és publikálnak; Ezek amennyire csak lehetséges nyílt forrásúak, hogy más fejlesztők tanulhassanak belőle. Rendszeresen blog hozzászólásokat, cikkeket, dokumentációt, könyveket, stb. írnak a Google platform-hoz tartozó témákkal kapcsolatban.\n\nMeglévő dokumentációt lefordítanak más nyelvekre, hogy a helyi fejlesztők megérthessék. A GDE-knek magas rangja van a fórumokon (mint pl. a Stack Overfow) és vezető hozzászólók a termék levelezési listákon.\n\nFejlesztői konferenciákon adnak elő, GDG-ket szerveznek és vezetnek, és hackathon-okat tartanak. A GDE-ket egy termékhez kapcsolódó, egy vagy több típusú említett tevékenység esetében lehet jelölni. Miután elfogadták a GDE jelölést, elvárhatóan továbbra is hozzájárulnak a közösséghez a fent felsorolt módokon.</string>
  <string name="no_nfc_use_qr_scanner">Az NFC nem található, használj QR kód leolvasót!</string>
  <string name="event_description">Leírás</string>
  <string name="event">Esemény</string>
  <string name="no_description_available"><![CDATA[<i>Nincs elérhető leírás</i>]]></string>
  <string name="starting_at">%1$s-kor kezdődik</string>
  <string name="loading_data_failed">Nem sikerült betölteni az események listáját..</string>
  <string name="share">Megosztás</string>
  <string name="open_event_site">Esemény oldal megtekintése</string>
  <string name="arrow_tagged">Megjelölt szervezőid</string>
  <string name="get_involved_translation_text">Ha szeretnél hozzájárulni az alkalmazás honosításához, azaz egy új nyelvre lefordítani vagy egy meglévőt fejleszteni, kérjük látogass el a crowdin oldalra\n\nhttps://crowdin.com/project/gdgx-frisbee</string>
  <string name="about_about">Az alkalmazásról</string>
  <string name="about_contributors">Közreműködők</string>
  <string name="about_translators">Fordítók</string>
  <string name="about_changelog">Változáslista</string>
  <string name="about_get_involved">Kapcsolódj be Te is</string>
  <string name="about_third_party_libraries">Külső könyvtárak</string>
  <string name="event_info">Információ</string>
  <string name="event_agenda">Napirend</string>
  <string name="event_more">Továbbiak</string>
  <string name="help">Súgó</string>
  <string name="feedback">Visszajelzés</string>
  <string name="feedback_cancel">Mégse</string>
  <string name="feedback_email_hint">E-mail címed</string>
  <string name="feedback_message_hint">Mi jár a fejedben?</string>
  <string name="feedback_send">Küldés</string>
  <string name="feedback_sending">Küldés…</string>
  <string name="for_leads">Vezetőknek</string>
  <string name="leads_welcome_title">Üdvözlet</string>
  <string name="leads_welcome">Mint GDG vezető elérheted ezeket a csak szervezőknek szóló segédleteket!</string>
  <string name="leads_resources_title">GDG Segédletek</string>
  <string name="leads_resources">Fontos GDG segédleteket találhatsz a Google Drive mappában. Koppints, hogy a tallózhasd a dia sorozatokat, útmutatókat, grafikákat, kód laboratóriumokat, stb.</string>
  <string name="leads_wisdom_title">GDG Bölcsességek GitBook</string>
  <string name="leads_wisdom">Ez a GitBook rengeteg általános információt tartalmaz a GDG fejezetek vezetéséről. Kérjük szerkeszd a lapokat, és járulj hozzá ehhez a globális mozgalomhoz. Koppints rá a GitBook megnyitásához.</string>
  <string name="leads_gplus_community_title">GDG Szervezők Kreatív Homokozója</string>
  <string name="leads_gplus_community">Ez a globális G+ közösség a GDG fejezetek működtetésének tapasztalatairól és ismereteiről szól. Koppintsál, hogy csatlakozhass a mozgalomhoz!</string>
  <string name="message">Üzenet</string>
  <string name="resource">Segédlet</string>
  <string name="cd_navdrawer_image">Navigációs Fiók Fejezet Kép</string>
  <string name="cd_navdrawer_user_picture">Felhasználói profil kép</string>
  <string name="title_signing_needed">Bejelentkezés szükséges</string>
  <string name="signin">Bejelentkezés</string>
  <string name="feedback_message_required">Üzenet szükséges</string>
  <string name="feedback_invalid_email">Érvényes email címet adj meg</string>
  <string name="drawer_subheader_games">Játékok</string>
  <string name="cd_arrowTagImage">Nyílas Jelölési Játék</string>
  <string name="cd_qrCode">QR kód</string>
  <string name="invitation_message">Töltsd le a GDG Android Alkalmazást, és fedezd fel a Google Fejlesztői Csoport tartalmakat amíg úton vagy. %s</string>
  <string name="invitation_error_message">Az Alkalmazás Meghívó sikertelen volt.</string>
  <string name="thanks_for_feedback">Köszönjük a visszajelzést!</string>
  <string name="retry">Újra próbál</string>
  <string name="title_event_series_greetings">Új esemény közeleg!</string>
  <string name="event_series_greetings">Tudj meg többet a %1$s-ról, és nézz meg az eseményeket a világ minden tájáról!</string>
  <string name="cd_invitation_sender_profile_image">Invitation sender profile image</string>
  <string name="invite_congrats">Yey! You\'re invited by\n%s</string>
  <string name="friend">a friend</string>
  <string name="login_register">Login/Register</string>
</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy PolicyId="urn:ndg:security:1.0:authz:test:policy"
    xmlns="urn:oasis:names:tc:xacml:2.0:policy:schema:cd:04"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:oasis:names:tc:xacml:2.0:policy:schema:cd:04 http://docs.oasis-open.org/xacml/access_control-xacml-2.0-policy-schema-cd-04.xsd"
    RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:permit-overrides">
    <Description>
        Test for not function.
    </Description>

    <!--
        The Policy target(s) define which requests apply to the whole policy
    -->
    <Target>
        <Resources>
            <Resource>
                <ResourceMatch MatchId="urn:oasis:names:tc:xacml:2.0:function:anyURI-regexp-match">
                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">^http://localhost/.*$</AttributeValue>
                    <ResourceAttributeDesignator
                        AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                        DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                </ResourceMatch>
            </Resource>
        </Resources>
    </Target>

    <!-- Deny everything by default -->
    <Rule RuleId="urn:ndg:security1.0:authz:test:DenyAllRule" Effect="Deny"/>

    <Rule RuleId="urn:ndg:security:test:function:and:1" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource1</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <!-- AND function with no arguments should evaluate to true. -->
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:2" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource2</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role1</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:3" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource3</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">norole1</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:4" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource4</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role1</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role2</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:5" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource5</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role1</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">norole2</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:6" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource6</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role1</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role2</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role3</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>

    <Rule RuleId="urn:ndg:security:test:function:and:7" Effect="Permit">
        <Target>
            <Resources>
                <Resource>
                    <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://localhost/resource7</AttributeValue>
                        <ResourceAttributeDesignator
                            AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                            DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
        </Target>
        <Condition>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role1</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">role2</AttributeValue>
                    </Apply>
                </Apply>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                    <SubjectAttributeDesignator
                        AttributeId="urn:ndg:security:authz:1.0:attr"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">norole3</AttributeValue>
                    </Apply>
                </Apply>
            </Apply>
        </Condition>
    </Rule>
</Policy>


text:
package org.jvnet.jaxb2_commons.xjc.outline;

import com.sun.codemodel.JType;
import com.sun.tools.xjc.outline.FieldAccessor;

public interface FieldAccessorEx extends FieldAccessor {

	public JType getType();

	public boolean isConstant();

	public boolean isVirtual();

	public boolean isAlwaysSet();
}


text: pub mod undirected;


text:
require "spec_helper"
require 'pry'

describe InpostParcelsTracker do
  it "has a version number" do
    expect(InpostParcelsTracker::VERSION).not_to be '1.0.2'
  end
end

describe 'Inpost::Parcel' do
  let(:mock_success) do
    file = File.join('spec', 'responses', 'success.json')
    JSON.parse(File.read(file)).with_indifferent_access
  end

  let(:mock_fail) do
    file = File.join('spec', 'responses', 'fail.json')
    JSON.parse(File.read(file)).with_indifferent_access
  end

  let(:success) { Inpost::Parcel.new('111111111111111111111111') }
  let(:failure) { Inpost::Parcel.new('222222222222222222222222') }
  let(:error) { Inpost::Parcel.new('123') }
  let(:empty) { Inpost::Parcel.new(nil) }

  context 'initialize' do
    it 'tracking code' do
      expect(success.instance_variables.blank?).to eq false
      expect(success.instance_values.values).to eq(%w(111111111111111111111111))
      expect { error }.to raise_error(RuntimeError)
      expect { empty }.to raise_error(RuntimeError)
    end
  end

  context 'track' do
    it 'returns json response - success' do
      allow(success).to receive_message_chain('track').and_return(mock_success)
      response = success.track
      expect(response.fetch('tracking_number')).to eq('111111111111111111111111')
      expect(response.fetch('status')).to eq('ready_to_pickup')
    end
    it 'returns json response - fail' do
      allow(failure).to receive_message_chain('track').and_return(mock_fail)
      response = failure.track
      expect(response.fetch('status')).to eq(404)
      expect(response.fetch('error')).to eq('resource_not_found')
    end
  end
end


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for OvfMissingElementNormalBoundary complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="OvfMissingElementNormalBoundary">
 *   <complexContent>
 *     <extension base="{urn:vim25}OvfMissingElement">
 *       <sequence>
 *         <element name="boundary" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OvfMissingElementNormalBoundary", propOrder = {
    "boundary"
})
public class OvfMissingElementNormalBoundary
    extends OvfMissingElement
{

    @XmlElement(required = true)
    protected String boundary;

    /**
     * Gets the value of the boundary property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBoundary() {
        return boundary;
    }

    /**
     * Sets the value of the boundary property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBoundary(String value) {
        this.boundary = value;
    }

}


text:
using System;
using System.ServiceModel;
using System.Threading.Tasks;
using NServiceBus;

#region CallbackService
[ServiceBehavior(
    InstanceContextMode = InstanceContextMode.Single,
    Name = "CallbackService")]
class CallbackService<TRequest, TResponse> : ICallbackService<TRequest, TResponse>
{
    IEndpointInstance endpointInstance;

    public CallbackService(IEndpointInstance endpointInstance)
    {
        this.endpointInstance = endpointInstance;
    }

    public async Task<TResponse> SendRequest(TRequest request)
    {
        SendOptions sendOptions = new SendOptions();
        sendOptions.RouteToThisEndpoint();
        return await endpointInstance.Request<TResponse>(request, sendOptions);
    }

    public void Dispose()
    {
        ((IDisposable)this).Dispose();
    }
}
#endregion


text:
import netifaces

def list_interfaces():
    broadcast_interfaces = {}

    interfaces = netifaces.interfaces()

    for entry in interfaces:
        try:
            entry_data = netifaces.ifaddresses(entry)[netifaces.AF_INET][0]

            if 'broadcast' in entry_data:
                broadcast_interfaces[entry] = entry_data
        except KeyError:
            pass

    return broadcast_interfaces

def get_iface_addr(interface):
    ip = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
    broadcast_ip = netifaces.ifaddresses(interface)[netifaces.AF_INET][0][
        'broadcast']

    return ip, broadcast_ip

def main():
    bcast_list = list_interfaces()
    print()
    print(bcast_list)

if __name__ == '__main__':
    main()


text:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace StructureDiagramming
{
	internal class PageConnector : Construct
	{
		private bool PointsToRight;
		public bool PointsRight
		{
			get
			{
				return this.PointsToRight;
			}
			set
			{
				this.PointsToRight = value;
			}
		}
		public PageConnector(bool PointsRight)
		{
			this.PointsToRight = PointsRight;
			base.Size = new Size(70, 50);
			this.BackColor = Color.White;
			base.ConstructType = ConstructType.PageConnector;
			if (this.PointsToRight)
			{
				base.TopConnectionPoint = new Point(0, 27);
				return;
			}
			base.TopConnectionPoint = new Point(70, 27);
		}
		public PageConnector(bool PointsRight, short Number)
		{
			this.PointsToRight = PointsRight;
			base.Size = new Size(70, 50);
			this.BackColor = Color.White;
			base.ConstructText = Convert.ToString(Number);
			base.ConstructType = ConstructType.PageConnector;
			if (this.PointsToRight)
			{
				base.TopConnectionPoint = new Point(0, 27);
				return;
			}
			base.TopConnectionPoint = new Point(70, 27);
		}
		public override void DrawConstuct(PaintEventArgs e)
		{
			Graphics graphics = e.Graphics;
			graphics.SmoothingMode = SmoothingMode.HighQuality;
			Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0), 2f);
			pen.Alignment = PenAlignment.Center;
			Rectangle r = default(Rectangle);
			if (this.PointsToRight)
			{
				graphics.DrawLine(pen, 1, 1, 50, 1);
				graphics.DrawLine(pen, 1, 1, 1, 49);
				graphics.DrawLine(pen, 1, 49, 50, 49);
				graphics.DrawLine(pen, 50, 1, 69, 25);
				graphics.DrawLine(pen, 50, 49, 69, 25);
				r = new Rectangle(new Point(10, 10), new Size(30, 30));
			}
			else
			{
				graphics.DrawLine(pen, 20, 1, 69, 1);
				graphics.DrawLine(pen, 69, 1, 69, 49);
				graphics.DrawLine(pen, 20, 49, 69, 49);
				graphics.DrawLine(pen, 1, 25, 20, 1);
				graphics.DrawLine(pen, 1, 25, 20, 49);
				r = new Rectangle(new Point(30, 10), new Size(30, 30));
			}
			StringFormat stringFormat = new StringFormat(StringFormatFlags.NoClip);
			stringFormat.LineAlignment = StringAlignment.Center;
			stringFormat.Alignment = StringAlignment.Center;
			Font font = new Font("Calibri", 8f);
			graphics.DrawString(base.ConstructText, font, Brushes.Black, r, stringFormat);
		}
		public Graphics PrintConstruct(Graphics Graphic)
		{
			Graphic.TranslateTransform((float)base.Location.X, (float)base.Location.Y);
			Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0), 2f);
			pen.Alignment = PenAlignment.Center;
			Rectangle r = default(Rectangle);
			if (this.PointsToRight)
			{
				Graphic.DrawLine(pen, 1, 1, 50, 1);
				Graphic.DrawLine(pen, 1, 1, 1, 49);
				Graphic.DrawLine(pen, 1, 49, 50, 49);
				Graphic.DrawLine(pen, 50, 1, 69, 25);
				Graphic.DrawLine(pen, 50, 49, 69, 25);
				r = new Rectangle(new Point(10, 10), new Size(30, 30));
			}
			else
			{
				Graphic.DrawLine(pen, 20, 1, 69, 1);
				Graphic.DrawLine(pen, 69, 1, 69, 49);
				Graphic.DrawLine(pen, 20, 49, 69, 49);
				Graphic.DrawLine(pen, 1, 25, 20, 1);
				Graphic.DrawLine(pen, 1, 25, 20, 49);
				r = new Rectangle(new Point(30, 10), new Size(30, 30));
			}
			StringFormat stringFormat = new StringFormat(StringFormatFlags.NoClip);
			stringFormat.LineAlignment = StringAlignment.Center;
			stringFormat.Alignment = StringAlignment.Center;
			Font font = new Font("Calibri", 8f);
			Graphic.DrawString(base.ConstructText, font, Brushes.Black, r, stringFormat);
			Graphic.TranslateTransform((float)(-(float)base.Location.X), (float)(-(float)base.Location.Y));
			return Graphic;
		}
	}
}


text:
package org.gradle.api.internal.artifacts.verification.verifier;

import org.gradle.internal.logging.text.TreeFormatter;

import java.io.File;

public class MissingChecksums extends AbstractVerificationFailure {
    public MissingChecksums(File file) {
        super(file);
    }

    @Override
    public void explainTo(TreeFormatter formatter) {
        formatter.append("checksum is missing from verification metadata.");
    }
}