text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.fuberlin.wiwiss.pubby</groupId>
  <artifactId>pubby</artifactId>
  <packaging>war</packaging>
  <version>0.4-SNAPSHOT</version>

  <name>Pubby</name>
  <description>A Linked Data Frontend for SPARQL Endpoints</description>
  <url>http://www4.wiwiss.fu-berlin.de/pubby/</url>
  <inceptionYear>2007</inceptionYear>

  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>https://raw.github.com/cygri/pubby/master/LICENSE.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <connection>scm:git:git@github.com:cygri/pubby.git</connection>
    <developerConnection>scm:git:git@github.com:cygri/pubby.git</developerConnection>
    <url>https://github.com/cygri/pubby/tree/master/</url>
  </scm>

  <developers>
    <developer>
      <id>cygri</id>
      <name>Richard Cyganiak</name>
      <email>richard@cyganiak.de</email>
      <url>http://richard.cyganiak.de/</url>
      <organization>DERI, NUI Galway</organization>
      <organizationUrl>http://www.deri.ie/</organizationUrl>
      <roles>
        <role>developer</role>
      </roles>
    </developer>
  </developers>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.4</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-arq</artifactId>
      <version>2.11.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.5</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>pubby</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.9.v20130131</version>
<!--
        <configuration>
          <webApp>
            <contextPath>/pubby</contextPath>
          </webApp>
        </configuration>
-->
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
            <descriptor>assembly.xml</descriptor>
          </descriptors>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
package org.apache.velocity.test.misc;

import java.io.IOException;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

/**
 * that always throws an exception.  Used to test
 * that RuntimeExceptions are passed through.
 *
 * @author Will Glass-Husain
 * @version $Id: ExceptionGeneratingDirective.java 463298 2006-10-12 16:10:32Z henning $
 */
public class ExceptionGeneratingDirective extends Directive
{

    public String getName()
    {
        return "Exception";
    }

    public int getType()
    {
        return Directive.BLOCK;
    }

    public boolean render(InternalContextAdapter context, Writer writer, Node node)
            throws IOException, ResourceNotFoundException, ParseErrorException,
            MethodInvocationException
    {
        throw new RuntimeException("exception");
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Load my models
var {mongoose} = require('../config/mongoose');
var {Requests} = require('../models/requests');
var {User} = require('../models/user');
var {Admin} = require('../models/admin');

module.exports = function(app) {

   /*
   *  Requests Page
   *  List all requests in the database
   */
  app.get('/requests', (req, res) => {
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    Requests.find().then((result) => {
      res.render('requests/all.hbs',{
        results : result,
        fullUrl : fullUrl,
        level : req.session.level

      });
    }, (e) => {
      res.status(400).send(e);
    });
  });

   /*
   *  New Request Page
   *  Creates a new request
   */
  app.get('/requests/new', (req, res) => {
    // Get a list of all users
    User.find().then((users) => {
      return res.render('requests/new.hbs', {
          adminName : req.session.name,
          level: req.session.level,
          users : users
      });
    }, (e) => {
      res.status(400).send(e);
    });

  });

  /*
   *  Process a new Request Request
   *  POST METHOD
   */
  app.post('/requests/new', (req, res) => {

      var request = new Requests({
         title: req.body.title,
         user_name: req.body.user_name,
         description: req.body.description,
         admin_name: req.body.admin_name,
         request_type: req.body.request_type,
         approved: req.body.approved || false
     });

    request.save().then((result) => {
        // Redirect to the requests page to show all
        Requests.find().then((result) => {

          var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

          res.render('requests/all.hbs',{
            results : result,
            message: "Great! The request has been successfully resolved",
            fullUrl: fullUrl,
            level : req.session.level
          });
        }, (e) => {
          res.status(400).send(e);
        });

    }, (e) => {
      // REQUEST: change to html page
      res.status(400).send(e);
    });

  });

   /*
   *  View Request Page
   *  View the request
   */
  app.get('/requests/:id', (req, res) => {

    var id = req.params.id;

    Requests.findById(id, (err, result) => {

        var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

        // Handle any possible database errors
        if (err) {
            res.status(500).send(err);
        } else {

          res.render('requests/view.hbs',{
            result : result,
            fullUrl: fullUrl,
            level : req.session.level
          });
        }
    });

  });

  app.get('/approve-request/:id', (req, res) => {

    var id = req.params.id;

    Requests.findById(id, (err, request) => {

        // Handle any possible database errors
        if (err) {
            res.status(500).send(err);
        } else {
            // Update each attribute with any possible attribute that may have been submitted in the body of the request
            // If that attribute isn't in the request body, default back to whatever it was before.
            request.approved = true;

            // Save the updated document back to the database
            request.save(function (err, request) {
                if (err) {
                    res.status(500).send(err)
                }

                var notify = new Notify({
                     title: request.title,
                     type : true,
                     request_id: id,
                 });

                notify.save().then((result) => {}, (e) => {});

                var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
                // Redirect to the requests page to show all
                Requests.find().then((result) => {
                  res.render('requests/all.hbs',{
                    results : result,
                    message: "The request has been successfully approved",
                    fullUrl: fullUrl,
                    level : req.session.level
                  });
                }, (e) => {
                  res.status(400).send(e);
                });

            });
        }
    });

  });

  app.get('/resolve-request/:id', (req, res) => {

    var id = req.params.id;

    Requests.findById(id, (err, request) => {

        // Handle any possible database errors
        if (err) {
            res.status(500).send(err);
        } else {
            // Update each attribute with any possible attribute that may have been submitted in the body of the request
            // If that attribute isn't in the request body, default back to whatever it was before.
            request.resolved = true;

            // Save the updated document back to the database
            request.save(function (err, request) {
                if (err) {
                    res.status(500).send(err)
                }

                var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

                // Redirect to the requests page to show all
                Requests.find().then((result) => {
                  res.render('requests/all.hbs',{
                    results : result,
                    message: "The request has been successfully resolved",
                    fullUrl: fullUrl,
                    level : req.session.level
                  });
                }, (e) => {
                  res.status(400).send(e);
                });

            });
        }
    });

  });

};


text:
package com.test_reactnative_nativemodules;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "Test_ReactNative_NativeModules";
    }
}


text:
package net.sourceforge.plantuml.sequencediagram.command;

import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexOptional;
import net.sourceforge.plantuml.command.regex.RegexOr;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.Stereotype;
import net.sourceforge.plantuml.graphic.color.ColorParser;
import net.sourceforge.plantuml.graphic.color.ColorType;
import net.sourceforge.plantuml.graphic.color.Colors;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
import net.sourceforge.plantuml.ugraphic.color.NoSuchColorException;

public class CommandBoxStart extends SingleLineCommand2<SequenceDiagram> {

	public CommandBoxStart() {
		super(getRegexConcat());
	}

	static IRegex getRegexConcat() {
		return RegexConcat.build(CommandBoxStart.class.getName(), RegexLeaf.start(), //
				new RegexLeaf("box"), //
				new RegexOptional(new RegexOr( //
						new RegexConcat( //
								RegexLeaf.spaceOneOrMore(), //
								new RegexLeaf("NAME1", "[%g]([^%g]+)[%g]")), //
						new RegexConcat( //
								RegexLeaf.spaceOneOrMore(), //
								new RegexLeaf("NAME2", "([^#]+)")))), //
				RegexLeaf.spaceZeroOrMore(), //
				new RegexLeaf("STEREO", "(\\<\\<.*\\>\\>)?"), //
				color().getRegex(), //
				RegexLeaf.end());
	}

	private static ColorParser color() {
		return ColorParser.simpleColor(ColorType.BACK);
	}

	@Override
	protected CommandExecutionResult executeArg(SequenceDiagram diagram, LineLocation location, RegexResult arg)
			throws NoSuchColorException {
//		if (diagram.isBoxPending())
//			return CommandExecutionResult.error("Box cannot be nested");

		final String argTitle = arg.getLazzy("NAME", 0);
		final String argColor = arg.get("COLOR", 0);

		final String stereo = arg.get("STEREO", 0);
		Stereotype stereotype = null;
		if (stereo != null) {
			final ISkinParam skinParam = diagram.getSkinParam();
			stereotype = Stereotype.build(stereo);
		}

		Colors colors = color().getColor(arg, diagram.getSkinParam().getIHtmlColorSet());
		final String title = argTitle == null ? "" : argTitle;
		diagram.boxStart(Display.getWithNewlines(title), colors.getColor(ColorType.BACK), stereotype);
		return CommandExecutionResult.ok();
	}

}


text:
package example;

import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;

public final class MainPanel extends JPanel {
  private MainPanel() {
    super(new BorderLayout());
    EventQueue.invokeLater(() -> {
      JMenuBar menuBar = new JMenuBar();
      menuBar.add(new JMenu("Menu 1")).add(makeSubMenu("SubMenu 1"));
      UIManager.put("Menu.arrowIcon", new ArrowIcon());
      menuBar.add(new JMenu("Menu 2")).add(makeSubMenu("SubMenu 2"));
      getRootPane().setJMenuBar(menuBar);
    });
    add(new JScrollPane(new JTextArea()));
    setPreferredSize(new Dimension(320, 240));
  }

  private static JMenu makeSubMenu(String title) {
    JMenu menu = new JMenu(title);
    menu.add("Item 1");
    menu.add("Item 2");
    menu.add("Item 3");
    // // NimbusLookAndFeel
    // UIDefaults d = new UIDefaults();
    // d.put("Menu.arrowIcon", new ArrowIcon());
    // menu.putClientProperty("Nimbus.Overrides", d);
    // menu.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
    return menu;
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(MainPanel::createAndShowGui);
  }

  private static void createAndShowGui() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      // // NimbusLookAndFeel
      // UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
      // UIManager.getLookAndFeelDefaults().put("Menu.arrowIcon", new ArrowIcon());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
      Toolkit.getDefaultToolkit().beep();
    }
    JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

class ArrowIcon implements Icon {
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    // // NimbusLookAndFeel
    // Container parent = SwingUtilities.getUnwrappedParent(c);
    // if (parent instanceof JMenuBar) {
    //   return;
    // }

    Graphics2D g2 = (Graphics2D) g.create();
    if (c instanceof AbstractButton && ((AbstractButton) c).getModel().isSelected()) {
      g2.setPaint(Color.WHITE);
    } else {
      g2.setPaint(Color.GRAY);
    }

    double w = getIconWidth() / 2d;
    Path2D p = new Path2D.Double();
    p.moveTo(0d, 0d);
    p.lineTo(w, w);
    p.lineTo(0d, getIconHeight());
    p.closePath();

    g2.translate(x, y);
    g2.fill(p);
    g2.dispose();
  }

  @Override public int getIconWidth() {
    return 8;
  }

  @Override public int getIconHeight() {
    return 8;
  }
}


text:
layout: post
title: Android知识点整理
categories: reading-notes
excerpt: Android知识点整理
tag: [Android, 面试, 知识点, 整理]
comments: true
image:
  feature: pic-book-1.jpg
---

Java 多线程:http://www.cnblogs.com/wxd0108/p/5479442.html

Android View继承关系:http://www.cnblogs.com/aademeng/articles/6539190.html

Activity、 Service、 Content Provider、Broadcast Receiver

service:http://blog.csdn.net/scott2017/article/details/51505801

动画:http://blog.csdn.net/seu_calvin/article/details/52724655

UI更新是否只能在主线程中?http://blog.csdn.net/happy_horse/article/details/52529140

android UI性能优化:http://mrpeak.cn/android/2016/01/11/android-performance-ui

apk加固原理:http://blog.csdn.net/jiangwei0910410003/article/details/48415225/

热更新:tinker

打包原理:https://tech.meituan.com/android-apk-v2-signature-scheme.html

BlockCanary,LeakCanary

Android Parcelable Serializable区别:http://www.cnblogs.com/yezhennan/p/5527506.html

FlatBuffers vs Protocol Buffer: http://blog.csdn.net/chosen0ne/article/details/43033575

Android-Architecture(MVP):
 https://github.com/googlesamples/android-architecture
http://www.jianshu.com/p/e0258ce7d392

第三方库:
日志: Logger、LogUtils、timber
JSON:gson、jackson、Fastjson、LoganSquare
数据库:greenDAO、Realm
网络:OkHttp、Volley、Retrofit
图片:Picasso、Glide、Freso
热更新:Dexposed、AndFix、Tinker、Nuwa

Android插件化:http://www.infoq.com/cn/articles/android-plug-ins-from-entry-to-give-up

RxJava & Agera:http://www.jianshu.com/p/d5c868e70703

Android反射机制:http://www.jianshu.com/p/7fdb8c828602

Kotlin & Anko:
https://github.com/mcxiaoke/awesome-kotlin
https://www.gitbook.com/book/huanglizhuo/kotlin-in-chinese/details

ReactNative

热更新:
http://www.jianshu.com/p/d17519d4952e
http://blog.csdn.net/u011200604/article/details/60143582

Facebook Buck构建工具

性能优化:
代码优化
图片优化
电量优化
布局优化
网络优化
内存优化
卡顿优化

调试工具:Facebook Stetho

APK压缩优化:Facebook Redex

单元测试:Robolectric

Android性能优化:http://www.csdn.net/article/2015-04-15/2824477-android-performance

Android AIDL:
http://blog.csdn.net/luoyanglizi/article/details/51980630
http://blog.csdn.net/luoyanglizi/article/details/52029091


text:
__author__ = 'Brian Wickman'

from pkg_resources import Requirement
from twitter.pants.base import Target

class PythonRequirement(Target):
  """Pants wrapper around pkg_resources.Requirement"""

  def __init__(self, requirement, dynamic=False, repository=None, name=None, version_filter=None):
    self._requirement = Requirement.parse(requirement)
    self._name = name or self._requirement.project_name
    self._dynamic = dynamic
    self._repository = repository
    self._version_filter = version_filter or (lambda: True)
    Target.__init__(self, self._name, False)

  def size(self):
    return 1

  def should_build(self):
    return self._version_filter()

  def __repr__(self):
    return 'PythonRequirement(%s)' % self._requirement


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Editor;

namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
    internal static class IEditorOptionsFactoryServiceExtensions
    {
        public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, SourceText text)
        {
            var textBuffer = text.Container.TryGetTextBuffer();
            if (textBuffer != null)
            {
                return editorOptionsFactory.GetOptions(textBuffer);
            }

            return editorOptionsFactory.GlobalOptions;
        }

        public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document)
        {
            if (document.TryGetText(out var text))
            {
                return editorOptionsFactory.GetEditorOptions(text);
            }

            return editorOptionsFactory.GlobalOptions;
        }

        // This particular section is commented for future reference if there arises a need to implement a option serializer in the editor layer
        // public static IOptionService GetFormattingOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document)
        // {
        //     return CreateOptions(editorOptionsFactory.GetEditorOptions(document));
        // }

        // private static IOptionService CreateOptions(IEditorOptions editorOptions)
        // {
        //     return new FormattingOptions(
        //        !editorOptions.IsConvertTabsToSpacesEnabled(),
        //        editorOptions.GetTabSize(),
        //        editorOptions.GetIndentSize());
        // }
    }
}


text:
package com.tianzhu.cms.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.tianzhu.cms.domain.constant.SystemConstant;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * @author Herbert
 *
 */
public class MediaUtils {

	private static Logger logger = Logger.getLogger(MediaUtils.class);

	/**
	 * 文件允许格式
	 */
	public static String[] FILE_TYPE = { ".rar", ".doc", ".docx", ".zip",
			".pdf", ".txt", ".swf", ".wmv" };

	/**
	 * 图片允许格式
	 */
	public static String[] PHOTO_TYPE = { ".gif", ".png", ".jpg", ".jpeg",
			".bmp" };

	public static boolean isFileType(String fileName, String[] typeArray) {
		for (String type : typeArray) {
			if (fileName.toLowerCase().endsWith(type)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 递归获得目录的所有地址
	 *
	 * @param realpath
	 * @param files
	 * @param fileType
	 * @return
	 */
	public static List<java.io.File> getFiles(String realpath,
			List<File> files, String[] fileType) {
		File realFile = new File(realpath);
		if (realFile.isDirectory()) {
			File[] subfiles = realFile.listFiles();
			for (File file : subfiles) {
				if (file.isDirectory()) {
					getFiles(file.getAbsolutePath(), files, fileType);
				} else {
					if (isFileType(file.getName(), fileType)) {
						files.add(file);
					}
				}
			}
		}
		return files;
	}

	/**
	 * 得到文件上传的相对路径
	 *
	 * @param fileName
	 *            文件名
	 * @return
	 */
	public static String getPath(String fileName) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
		String uploadPath = "upload/" + formater.format(new Date()) + "/"
				+ UUID.randomUUID().toString().replaceAll("-", "")
				+ getFileExt(fileName);
		return uploadPath;
	}

	/**
	 * 获取文件扩展名
	 *
	 * @return string
	 */
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 删除物理文件
	 *
	 * @param path
	 */
	public static void deleteFile(String path) {
		File file = new File(SystemConstant.SHISHUO_CMS_ROOT + path);
		file.delete();
	}

	/**
	 * 保存,并裁剪图片
	 *
	 * @param multipartFile
	 * @param width
	 * @param height
	 * @throws IOException
	 */
	public static String saveImage(MultipartFile multipartFile, int width,
			int height) throws IOException {
		logger.info("压缩图片尺寸:"+width+" x "+height);
		SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
		String path = "upload/" + formater.format(new Date()) + "/"
				+ UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
		String filePath = SystemConstant.SHISHUO_CMS_ROOT + "/" + path;
		File file = new File(SystemConstant.SHISHUO_CMS_ROOT + "/" + path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		if (width > 0 && height > 0) {
			BufferedImage bufferedImage = ImageIO.read(multipartFile
					.getInputStream());
			int imageWidth = bufferedImage.getWidth();
			int imageHeitht = bufferedImage.getHeight();
			BufferedImage image = null;
			if (width / height < imageWidth / imageHeitht) {
				image = Thumbnails.of(multipartFile.getInputStream())
						.height(height).asBufferedImage();
			} else {
				image = Thumbnails.of(multipartFile.getInputStream())
						.width(width).asBufferedImage();
			}
			Thumbnails.of(image).sourceRegion(Positions.CENTER, width, height)
					.size(width, height).outputFormat("jpg").toFile(filePath);

		} else {
			if (width == 0 && height == 0) {
				multipartFile.transferTo(file);
			} else {
				if (width > 0) {
					Thumbnails.of(multipartFile.getInputStream()).width(width)
							.keepAspectRatio(true).outputFormat("jpg")
							.toFile(filePath);
				}
				if (height > 0) {
					Thumbnails.of(multipartFile.getInputStream())
							.height(height).keepAspectRatio(true)
							.outputFormat("jpg").toFile(filePath);
				}
			}
		}
		// FileOutputStream fos = new FileOutputStream(file);
		// baos.writeTo(fos);
		return path;
	}

	/**
	 * @param multipartFile
	 * @return
	 */
	public static String save(MultipartFile multipartFile) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
		String path = "upload/" + formater.format(new Date()) + "/"
				+ UUID.randomUUID().toString().replaceAll("-", "")
				+ getFileExt(multipartFile.getOriginalFilename());
		File file = new File(SystemConstant.SHISHUO_CMS_ROOT + "/" + path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		return path;
	}

}


text:
package shred.man.cuda.nn.train

import breeze.linalg.{DenseVector, DenseMatrix}
import shred.man.cuda.cumath.CuFloat
import shred.man.cuda.cumath.tensor.matrix.{CublasMatrix, CuMatrix}
import shred.man.cuda.cumath.tensor.vector.CuVector
import shred.man.cuda.driver.{CuDisposable, CuContext}
import shred.man.cuda.nn.activation.Activation
import shred.man.cuda.nn.cost.LogErrorCost
import shred.man.nn.layers.FullyConnectedLayer
import shred.man.cuda.cumath.tensor.matrix.ops.module.CuMatrixBroadcast

object FullyConnected
{
  class BackPropTrainer(layer: FullyConnectedLayer, activation: Activation, samplesLength: Int, learnRate: Double, regRate: Double)
                       (implicit ctx: CuContext) extends LayerTrainer[FullyConnectedLayer] with CuDisposable
  {
    private val costCalc = new LogErrorCost(samplesLength, layer.size)

    private val one = CuFloat(1f)
    private val zero = CuFloat(0f)
    private val negOne = CuFloat(-1f)

    private val rate = CuFloat((regRate * learnRate).toFloat)
    private val coeff = CuFloat((learnRate / samplesLength).toFloat)

    private val wT = CuMatrix(layer.wT.rows, layer.wT.cols, layer.wT.data.map(_.toFloat))
    private val b = CuVector(layer.b.data.map(_.toFloat))

    private val gradWT = CuMatrix(wT.rows, wT.cols)
    private val gradB = CuVector(b.size)

    private val z: CuMatrix = CuMatrix(samplesLength, layer.size)
    private val neuronErr: CuMatrix = CuMatrix(samplesLength, layer.size)
    private val prevActErr: CuMatrix = CuMatrix(samplesLength, wT.rows)

    // created and disposed in activation
    private var x: CuMatrix = null
    private var a: CuMatrix = null

    private val matBcst = new CuMatrixBroadcast

    private def regularization(): Double = {
      // TODO: lol WUT?
      val res = CuFloat(0f)
      res =: wT.flatten * wT.flatten
      val v = res.load() * regRate * 0.5

      res.dispose()
      v
    }

    override def init(y: CuMatrix) = {
      val initNeuronErr = costCalc.derivative(y, a, activation.derivative(z))
      update(initNeuronErr)
      prevActErr =: initNeuronErr * wT.t
      prevActErr
    }

    override def back(actErr: CuMatrix) = {
      matBcst.elemWiseMult(actErr, activation.derivative(z), neuronErr)
      update(neuronErr)
      prevActErr =: neuronErr * wT.t
      prevActErr
    }

    override def forward(x: CuMatrix) = {
      this.x = x
      z =: x * wT
      matBcst.rowWiseAdd(z, b, z)
      a = activation(z)
      a
    }

    private def update(neuronErr: CuMatrix) {
      gradWT =: x.t * neuronErr
      matBcst.colWiseSum(neuronErr, gradB)

      CublasMatrix.geam(coeff, gradWT, rate, wT, gradWT)
      gradB *= coeff

      wT :-= gradWT
      b -= gradB
    }

    override def cost(y: CuMatrix): Double = costCalc(a, y, regularization())

    override def syncLayer() {
      layer.wT := DenseMatrix.create(wT.rows, wT.cols, wT.fetch().map(_.toDouble))
      layer.b := DenseVector(b.fetch().map(_.toDouble))
    }

    override def disposeInternal() {
      matBcst.dispose()

      gradWT.dispose()
      gradB.dispose()

      wT.dispose()
      b.dispose()

      z.dispose()
      neuronErr.dispose()
      prevActErr.dispose()

      one.dispose()
      zero.dispose()
      negOne.dispose()

      coeff.dispose()
      rate.dispose()

      costCalc.dispose()
    }
  }
}


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Article;
use AppBundle\Entity\Comment;
use AppBundle\Form\CommentType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

class BlogController extends Controller
{
    /**
     * Lists all article entities.
     *
     * @Route("/", name="blog_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $qb = $this->getDoctrine()
            ->getManager()
            ->createQueryBuilder()
            ->from('AppBundle:Article', 'p')
            ->select('p');

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $qb,
            $request->query->get('page', 1),
            20
        );

        return $this->render('blog/index.html.twig', array(
            'articles' => $pagination,
        ));
    }

    /**
     * Creates a new article entity.
     *
     * @Route("/article/new", name="article_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $article = new Article();
        $article->setUser($user = $this->getUser());
        $form = $this->createForm('AppBundle\Form\ArticleType', $article);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($article);
            $em->flush($article);

            $this->get('session')->getFlashBag()->set('success', 'New article was successfull created.');
            return $this->redirectToRoute('article_show', array('id' => $article->getId()));
        }

        return $this->render('blog/new.html.twig', array(
            'article' => $article,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a article entity.
     *
     * @Route("/article/{id}", name="article_show")
     * @Method({"GET", "POST"})
     */
    public function showAction(Article $article, Request $request)
    {
        $form = null;

        if($user = $this->getUser()){

            $comment = new Comment();
            $comment->setArticle($article);
            $comment->setUser($user);

            $form = $this->createForm('AppBundle\Form\CommentType', $comment);
            $form->handleRequest($request);

            if ($form->isValid()){
                $em = $this->getDoctrine()->getManager();
                $em->persist($comment);
                $em->flush();

                $this->addFlash('success', 'New comment added');

                return $this->redirectToRoute('article_show', array('id' => $article->getId()));
            }
        }
        $deleteForm = $this->createDeleteForm($article);

        return $this->render('blog/show.html.twig', array(
            'article' => $article,
            'comment_create_form' => is_null($form) ? $form : $form->createView(),
            'article_delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing article entity.
     *
     * @Route("/article/{id}/edit", name="article_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Article $article)
    {
        if($article->getUser() === $this->getUser()){
            $editForm = $this->createForm('AppBundle\Form\ArticleType', $article);
            $editForm->handleRequest($request);

            if ($editForm->isSubmitted() && $editForm->isValid()) {
                $this->getDoctrine()->getManager()->flush();

                $this->get('session')->getFlashBag()->set('success', 'New article was successfull modified.');

                return $this->redirectToRoute('article_show', array('id' => $article->getId()));
            }

            return $this->render('blog/edit.html.twig', array(
                'article' => $article,
                'edit_form' => $editForm->createView()
            ));
        } else {
            $this->get('session')->getFlashBag()->set('danger', 'Access denied. You are not author of this article.');

            return $this->redirectToRoute('blog_index');
        }

    }

    /**
     * Deletes a article entity.
     *
     * @Route("/article/{id}", name="article_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Article $article)
    {
        if($article->getUser() === $this->getUser()){
            $form = $this->createDeleteForm($article);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->remove($article);
                $em->flush();

                $this->get('session')->getFlashBag()->set('success', 'Article was successfull deleted.');

                return $this->redirectToRoute('blog_index');
            }

            $this->get('session')->getFlashBag()->set('danger', 'Error Invalid data.');

        } else {
            $this->get('session')->getFlashBag()->set('danger', 'Access denied. You are not author of this article.');
        }

        return $this->redirectToRoute('article_show', array('id' => $article->getId()));
    }

    /**
     * Creates a form to delete a article entity.
     *
     * @param Article $article The article entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Article $article)
    {
        return $this->createFormBuilder(null, array('attr' => array('class' => 'inline-form')))
            ->setAction($this->generateUrl('article_delete', array('id' => $article->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.

using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("TestingHelpers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Google Cloud")]
[assembly: AssemblyProduct("Cloud Tools for Visual Studio")]
[assembly: AssemblyCopyright("Copyright © Google Inc. 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]
[assembly: Guid("4eb5a3a0-3d68-4880-8855-405a46cdce0b")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
package org.zalando.logbook;

import org.junit.jupiter.api.Test;

import java.io.IOException;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;

final class ResponseFiltersTest {

    @Test
    void shouldReplaceImageBodyByDefault() throws IOException {
        final ResponseFilter filter = ResponseFilters.defaultValue();

        final HttpResponse response = filter.filter(MockHttpResponse.create()
                .withContentType("image/png")
                .withBodyAsString("this is an image"));

        response.withBody();

        assertThat(response.getContentType()).isEqualTo("image/png");
        assertThat(response.getBody()).isEqualTo("<binary>".getBytes(UTF_8));
        assertThat(response.getBodyAsString()).isEqualTo("<binary>");
    }

    @Test
    void shouldReplaceImageBodyEvenWithoutBody() throws IOException {
        final ResponseFilter filter = ResponseFilters.defaultValue();

        final HttpResponse response = filter.filter(MockHttpResponse.create()
                .withContentType("image/png")
                .withBodyAsString("this is an image"));

        response.withoutBody();

        assertThat(response.getContentType()).isEqualTo("image/png");
        assertThat(response.getBody()).isEqualTo("<binary>".getBytes(UTF_8));
    }

    @Test
    void shouldNotReplaceTextBodyByDefault() throws IOException {
        final ResponseFilter filter = ResponseFilters.defaultValue();

        final HttpResponse response = filter.filter(MockHttpResponse.create()
                .withContentType("text/plain")
                .withBodyAsString("Hello"));

        response.withBody();

        assertThat(response.getBody()).isEqualTo("Hello".getBytes(UTF_8));
        assertThat(response.getBodyAsString()).isEqualTo("Hello");
    }

}


text:
<?php

/**
 * Module defines proprietary tags and attributes in HTML.
 * @warning If this module is enabled, standards-compliance is off!
 */
class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule
{
    /**
     * @type string
     */
    public $name = 'Proprietary';

    /**
     * @param HTMLPurifier_Config $config
     */
    public function setup($config)
    {
        $this->addElement(
            'marquee',
            'Inline',
            'Flow',
            'Common',
            array(
                'direction' => 'Enum#left,right,up,down',
                'behavior' => 'Enum#alternate',
                'width' => 'Length',
                'height' => 'Length',
                'scrolldelay' => 'Number',
                'scrollamount' => 'Number',
                'loop' => 'Number',
                'bgcolor' => 'Color',
                'hspace' => 'Pixels',
                'vspace' => 'Pixels',
            )
        );
    }
}

// vim: et sw=4 sts=4


text:
from __future__ import absolute_import

import datetime
import responses
import pytest
import six

from django.utils import timezone
from exam import fixture
from sentry.models import Integration, Repository
from sentry.testutils import TestCase, IntegrationRepositoryTestCase
from sentry.integrations.bitbucket.repository import BitbucketRepositoryProvider
from sentry.shared_integrations.exceptions import IntegrationError
from .testutils import COMPARE_COMMITS_EXAMPLE, COMMIT_DIFF_PATCH, REPO

class BitbucketRepositoryProviderTest(TestCase):
    def setUp(self):
        super(BitbucketRepositoryProviderTest, self).setUp()
        self.base_url = "https://api.bitbucket.org"
        self.shared_secret = "234567890"
        self.subject = "connect:1234567"
        self.integration = Integration.objects.create(
            provider="bitbucket",
            external_id=self.subject,
            name="MyBitBucket",
            metadata={
                "base_url": self.base_url,
                "shared_secret": self.shared_secret,
                "subject": self.subject,
            },
        )
        self.integration.add_organization(self.organization, self.user)
        self.repo = Repository.objects.create(
            provider="bitbucket",
            name="sentryuser/newsdiffs",
            organization_id=self.organization.id,
            config={"name": "sentryuser/newsdiffs"},
            integration_id=self.integration.id,
        )

    @fixture
    def provider(self):
        return BitbucketRepositoryProvider("bitbucket")

    def test_get_client(self):
        installation = self.integration.get_installation(self.repo.organization_id)
        client = installation.get_client()
        assert client.base_url == self.base_url
        assert client.shared_secret == self.shared_secret
        assert client.subject == self.subject

    @responses.activate
    def test_compare_commits(self):
        responses.add(
            responses.GET,
            "https://api.bitbucket.org/2.0/repositories/sentryuser/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301",
            body=COMPARE_COMMITS_EXAMPLE,
        )
        responses.add(
            responses.GET,
            "https://api.bitbucket.org/2.0/repositories/sentryuser/newsdiffs/diff/e18e4e72de0d824edfbe0d73efe34cbd0d01d301",
            body=COMMIT_DIFF_PATCH,
        )

        res = self.provider.compare_commits(
            self.repo, None, "e18e4e72de0d824edfbe0d73efe34cbd0d01d301"
        )

        assert res == [
            {
                "author_email": "sentryuser@getsentry.com",
                "author_name": "Sentry User",
                "message": "README.md edited online with Bitbucket",
                "id": "e18e4e72de0d824edfbe0d73efe34cbd0d01d301",
                "repository": "sentryuser/newsdiffs",
                "patch_set": [{"path": u"README.md", "type": "M"}],
                "timestamp": datetime.datetime(2017, 5, 16, 23, 21, 40, tzinfo=timezone.utc),
            }
        ]

    @responses.activate
    def test_build_repository_config(self):
        full_repo_name = "laurynsentry/helloworld"
        webhook_id = "web-hook-id"
        responses.add(
            responses.GET,
            "https://api.bitbucket.org/2.0/repositories/%s" % full_repo_name,
            json=REPO,
        )
        responses.add(
            responses.POST,
            "https://api.bitbucket.org/2.0/repositories/%s/hooks" % full_repo_name,
            json={"uuid": webhook_id},
            status=201,
        )

        organization = self.create_organization()
        integration = Integration.objects.create(
            provider="bitbucket",
            external_id="bitbucket_external_id",
            name="Hello world",
            metadata={"base_url": "https://api.bitbucket.org", "shared_secret": "23456789"},
        )
        integration.add_organization(organization)
        data = {
            "provider": "integrations:bitbucket",
            "identifier": full_repo_name,
            "installation": integration.id,
        }
        data = self.provider.get_repository_data(organization, data)
        assert data == {
            "provider": "integrations:bitbucket",
            "identifier": full_repo_name,
            "installation": integration.id,
            "external_id": REPO["uuid"],
            "name": full_repo_name,
        }
        data = self.provider.build_repository_config(organization, data)

        assert data == {
            "name": full_repo_name,
            "external_id": REPO["uuid"],
            "url": "https://bitbucket.org/laurynsentry/helloworld",
            "integration_id": integration.id,
            "config": {"name": full_repo_name, "webhook_id": webhook_id},
        }

    def test_repository_external_slug(self):
        result = self.provider.repository_external_slug(self.repo)
        assert result == self.repo.name

    def test_get_repository_data_no_installation_id(self):
        with pytest.raises(IntegrationError) as e:
            self.provider.get_repository_data(self.organization, {})
            assert "requires an integration id" in six.text_type(e)

class BitbucketCreateRepositoryTestCase(IntegrationRepositoryTestCase):
    provider_name = "integrations:bitbucket"

    def setUp(self):
        super(BitbucketCreateRepositoryTestCase, self).setUp()
        self.base_url = "https://api.bitbucket.org"
        self.shared_secret = "234567890"
        self.subject = "connect:1234567"
        self.integration = Integration.objects.create(
            provider="bitbucket",
            external_id=self.subject,
            name="MyBitBucket",
            metadata={
                "base_url": self.base_url,
                "shared_secret": self.shared_secret,
                "subject": self.subject,
            },
        )
        self.integration.get_provider().setup()
        self.integration.add_organization(self.organization, self.user)
        self.repo = Repository.objects.create(
            provider="bitbucket",
            name="sentryuser/newsdiffs",
            organization_id=self.organization.id,
            config={"name": "sentryuser/newsdiffs"},
            integration_id=self.integration.id,
        )
        self.default_repository_config = {"full_name": "getsentry/example-repo", "id": "123"}

    def add_create_repository_responses(self, repository_config):
        responses.add(
            responses.GET,
            "%s/2.0/repositories/%s" % (self.base_url, self.repo.name),
            json=repository_config,
        )
        responses.add(
            responses.POST,
            u"%s/2.0/repositories/%s/hooks" % (self.base_url, self.repo.name),
            json={"uuid": "99"},
        )

    def test_create_repository_data_no_installation_id(self):
        response = self.create_repository(self.default_repository_config, None)
        assert response.status_code == 400
        self.assert_error_message(response, "validation", "requires an integration id")

    def test_create_repository_data_integration_does_not_exist(self):
        integration_id = self.integration.id
        self.integration.delete()

        response = self.create_repository(self.default_repository_config, integration_id)
        assert response.status_code == 404
        self.assert_error_message(
            response, "not found", "Integration matching query does not exist."
        )


text:
module Statistics
  module Bootstrap

    Cache = Struct.new(:weight, :length, :series)
    @@cache = Cache.new(nil, nil, nil)

    private
    class WeightedArray < Array
      def initialize(other_array, weights)
        total_weights = weights.inject(0.0) { |t,e| t+e }
        proportions = weights.map { |e| e / total_weights }

        elements = other_array.zip(proportions)

        # construct an alias table for faster access
        @table = []

        n = elements.size
        elements.map! { |a,w| [a, w*(n-1)]}
        elements = elements.sort_by { |e| e[1] }

        while elements.size > 2
          p = elements[0][1]
          elements[-1][1] -= p
          @table << [p, elements[0][0], elements[-1][0]]
          elements.delete_at(0)
          elements.sort! { |a,b| a[1] <=> b[1] }
        end

        p = elements[0][1]
        elements[-1][1] -= (1.0 - p) #subtract the complement
        @table << [p, elements[0][0], elements[-1][0]]
      end

      def random_element
        entry = @table[(Kernel.rand * @table.size).floor]
        if Kernel.rand < entry[0]
          return entry[1]
        else
          return entry[2]
        end
      end

      def random_elements_with_vec(v)
        n = v.size / 2
        entries = Array.new(n)
        n.times { |i|
          entry = @table[(v[i*2] * @table.size).floor]
          entries[i] = v[i*2 + 1] < entry[0] ? entry[1] : entry[2]
        }

        return entries
      end
    end

    public
    # reference http://www.smartfolio.com/theory/details/appendices/a/
    # Ideally here, we would do a weighted random system where the weight
    # choice becomes smoother the further we get away from the present
    #
    # ideally, we want to pick from the last 10 years (10*250 days),
    # which on a daily basis is a decay weight x solving
    #                              0.00001 = x**2500
    # =>                  log(0.0001)/2500 = log(x)
    # =>             e^(log(0.0001)/2500)) = x
    def self.block_bootstrap(returns, target_length, block_size = 20,
                                      n = 2500, weight_factor = 0.998401279)
      raise "Target length must be even multiple of block size" unless (target_length % block_size == 0)

      returns_as_array = returns.to_a
      total_blocks = returns_as_array.size - block_size

      #TODO: weighted blocks should be recomputed every time a block is
      #      placed?

      # cache the series so we don't have to construct it multiple times if
      # we are doing it with the same weight factor
      if @@cache[:weight].nil? || weight_factor != @@cache[:weight] || @@cache[:length] != total_blocks
        weights = (0..total_blocks).map { |i| weight_factor**i }.reverse
        #blocks = []
        #total_blocks.times { |i|
        #  blocks << returns_as_array[i...(i+block_size)]
        #}
        blocks = (0..total_blocks).to_a
        @@cache[:series] = WeightedArray.new(blocks, weights)
        @@cache[:weight] = weight_factor
        @@cache[:length] = total_blocks
      end

      r = GSL::Rng.alloc
      indices = GSL::Matrix.alloc(n, target_length / block_size)
      n.times { |i|
        #overwrite our row with random blocks
        v = r.uniform(2 * target_length / block_size)

        row = @@cache[:series].random_elements_with_vec(v)
        #transform it to a vector
        vec = GSL::Vector[*row.flatten]
        #insert it into the series matrix
        indices.set_row(i, vec)
      }
      return indices
    end
  end
end


text:
[![NPM Version](https://img.shields.io/npm/v/amqper.svg?style=flat)](https://www.npmjs.org/package/amqper)
[![Build Status](http://img.shields.io/travis/taoyuan/amqper.svg?style=flat)](https://travis-ci.org/taoyuan/amqper)
[![Coverage](https://coveralls.io/repos/taoyuan/amqper/badge.svg?branch=master)](https://coveralls.io/r/taoyuan/amqper)
[![Quality](https://codeclimate.com/github/taoyuan/amqper/badges/gpa.svg)](https://codeclimate.com/github/taoyuan/amqper)
[![Dependencies](https://img.shields.io/david/taoyuan/amqper.svg?style=flat)](https://david-dm.org/taoyuan/amqper)

> A simple and elegant AMQP client for node based on amqplib.

## Install

```sh
$ npm install --save amqper
```

## Usage

### round-robin

Run multiple consumer.js for round-robin shared.

__consumer.js__

```js
var amqper = require('amqper');

var client = amqper.connect('amqp://guest:guest@localhost:5672');

client.route('test.a', {}, function (message) {
  console.log(message.payload);
});

```

__producer.js__

```js
var amqper = require('amqper');

var client = amqper.connect('amqp://guest:guest@localhost:5672');

for (var i = 0; i < 10; i++) {
  client.publish('amq.topic', 'test.a', i);
}

```

## License

MIT © [Tao Yuan]()


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QHXYMODELMAPPERSLOTS_H
#define QHXYMODELMAPPERSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>

#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
#include <QtCharts/QHXYModelMapper>
#endif

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

using namespace QtCharts;

class QHXYModelMapperSlots: public QObject
{
  Q_OBJECT
  public:
  QHXYModelMapperSlots( QObject *parent = 0 );
  ~QHXYModelMapperSlots();
  public slots:
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void columnCountChanged();
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void firstColumnChanged();
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void modelReplaced();
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void seriesReplaced();
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void xRowChanged();
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
  void yRowChanged();
#endif
};

#endif /* QHXYMODELMAPPERSLOTS_H */


text:
                       Edit Admin

Administrator Control

Edit Admin

                                <form role="form" enctype="multipart/form-data" action="<?php echo site_url('KelolaAdmin/edit_admin/'.$idAdmin);?>" method="POST">

                                            <?php if($this->session->flashdata('msg_gagal')!=''){?>

                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                                    <?php echo $this->session->flashdata('msg_gagal');?>

                                            <?php }?>

										<?php if($dataAdmin['status_admin']!='Super Admin'){?>

                                            Status Admin :

                                            <select name="status_admin" required class="form-control" id="status_admin">
                                                <option value="">--Pilih Status Admin--</option>
                                                <?php
                                                    foreach ($status_admin as $key=>$status_admin)
                                                    {
                                                        if ($key==$dataAdmin['status_admin']){
                                                            echo '<option value="'.$key.'" selected>'.$status_admin.'</option>';
                                                        }
                                                        else
                                                        {
                                                            echo '<option value="'.$key.'">'.$status_admin.'</option>';
                                                        }
                                                    }
                                                ?>
                                            </select>

										<?php } else {?>
										<input type="hidden" value="<?php echo $dataAdmin['status_admin'];?>" name="status_admin">
										<?php } ?>

                                            Username :
                                            <input type="text" required name="username" class="form-control" id="exampleInputEmail1" value="<?php echo htmlspecialchars($dataAdmin['username']); ?>">

                                            Nama Admin :
                                            <input type="text" required name="nama_admin" class="form-control" id="exampleInputEmail1" value="<?php echo htmlspecialchars($dataAdmin['nama_admin']); ?>">

                                            Email :
                                            <input type="text" required name="email" class="form-control" id="exampleInputEmail1" value="<?php echo htmlspecialchars($dataAdmin['email']); ?>">

                                            Telfon :
                                            <input type="text" required name="telfon" class="form-control" id="exampleInputEmail1" value="<?php echo htmlspecialchars($dataAdmin['telfon']); ?>">

                                            Reset Password ?

                                            Password Baru :
                                            <input type="hidden" required name="passwordbaru" class="form-control" id="password1">

											Ulangi Password Baru :
                                            <input type="hidden" required name="re_password" class="form-control" id="password2" onkeyup="validate()">

                                            Foto Admin :

                                            <img style="height: 250px; padding: 4px; max-width:250px; border: solid 1px black" src="<?php echo base_url('asset/upload_img_admin/'.$dataAdmin['path_foto']); ?>"/>

                                        Ganti Gambar ?

                                            <input class="form" type="file" name="filefoto" >

File diizinkan: jpg, jpeg, dan png (Max 2Mb)

                                    <input type="hidden" name="id_admin" value="<?php echo $idAdmin; ?>">
                                    <input type="hidden" name="passwordlama" value="<?php echo htmlspecialchars($dataAdmin['password']); ?>">

                                        <button type="submit" name="save" value="1" class="btn btn-primary"id="submitSave"> Simpan</button>
                                       <a href="<?php echo site_url('KelolaAdmin/');?>"><button type="button" name="submit" class="btn btn-danger">Batal</button>

                                </form>


text:
"""
Represents MDGX force field parameterization data
"""
################################### MODULES ###################################
from __future__ import (absolute_import, division, print_function,
    unicode_literals)

if __name__ == "__main__":
    __package__ = str("moldynplot.dataset")
    import moldynplot.dataset
from IPython import embed
import h5py
import numpy as np
import pandas as pd
from ..myplotspec.Dataset import Dataset
from ..myplotspec import sformat, wiprint

################################### CLASSES ###################################
class MDGXDataset(Dataset):
    """
    Represents MDGX force field parameterization data
    """

    @classmethod
    def get_cache_key(cls, infile, selections=None, *args, **kwargs):
        """
        Generates tuple of arguments to be used as key for dataset
        cache.

        .. todo:
          - Verify that keyword arguments passed to pandas may be safely
            converted to hashable tuple, and if they cannot throw a
            warning and load dataset without memoization
        """
        from os.path import expandvars

        read_csv_kw = []
        for key, value in kwargs.get("read_csv_kw", {}).items():
            if isinstance(value, list):
                value = tuple(value)
            read_csv_kw.append((key, value))
        return (
            cls, expandvars(infile), tuple(selections), tuple(read_csv_kw))

    def __init__(self, infile, selections=None, **kwargs):
        """
        """
        from os.path import expandvars

        # Load
        super(MDGXDataset, self).__init__(infile=infile, **kwargs)
        dataframe = self.dataframe
        dataframe.index.name = "conformation"
        dataframe["error"] = np.abs(
          dataframe["qm_energy"] - dataframe["mm_energy"])

        selection_dataframes = []
        if selections is not None:
            for selection in selections:
                selection_dataframes.append(dataframe[
                    dataframe["topology"].str.endswith("/" + selection)])
        self.selections = selection_dataframes

#################################### MAIN #####################################
if __name__ == "__main__":
    MDGXDataset.main()


text:
package main

import (
	"flag"
	"testing"

	"go.etcd.io/etcd/client/pkg/v3/testutil"
	"go.etcd.io/etcd/tests/v3/functional/tester"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"go.uber.org/zap/zaptest"
)

var config = flag.String("config", "../../functional.yaml", "path to tester configuration")

func TestFunctional(t *testing.T) {
	testutil.SkipTestIfShortMode(t, "functional tests are skipped in --short mode")

	lg := zaptest.NewLogger(t, zaptest.Level(zapcore.InfoLevel)).Named("tester")

	clus, err := tester.NewCluster(lg, *config)
	if err != nil {
		t.Fatalf("failed to create a cluster: %v", err)
	}

	if err = clus.Send_INITIAL_START_ETCD(); err != nil {
		t.Fatal("Bootstrap failed", zap.Error(err))
	}

	t.Log("wait health after bootstrap")
	if err = clus.WaitHealth(); err != nil {
		t.Fatal("WaitHealth failed", zap.Error(err))
	}

	if err := clus.Run(t); err == nil {
		// Only stop etcd and cleanup data when test is successful.
		clus.Send_SIGQUIT_ETCD_AND_REMOVE_DATA()
	}
}


text:
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER

DeepScanLineOutputPart::DeepScanLineOutputPart(MultiPartOutputFile& multiPartFile, int partNumber)
{
    file = multiPartFile.getOutputPart<DeepScanLineOutputFile>(partNumber);
}

const char *
DeepScanLineOutputPart::fileName () const
{
    return file->fileName();
}

const Header &
DeepScanLineOutputPart::header () const
{
    return file->header();
}

void
DeepScanLineOutputPart::setFrameBuffer (const DeepFrameBuffer &frameBuffer)
{
    file->setFrameBuffer(frameBuffer);
}

const DeepFrameBuffer &
DeepScanLineOutputPart::frameBuffer () const
{
    return file->frameBuffer();
}

void
DeepScanLineOutputPart::writePixels (int numScanLines)
{
    file->writePixels(numScanLines);
}

int
DeepScanLineOutputPart::currentScanLine () const
{
    return file->currentScanLine();
}

void
DeepScanLineOutputPart::copyPixels (DeepScanLineInputFile &in)
{
    file->copyPixels(in);
}

void
DeepScanLineOutputPart::copyPixels (DeepScanLineInputPart &in)
{
    file->copyPixels(in);
}

void
DeepScanLineOutputPart::updatePreviewImage (const PreviewRgba newPixels[])
{
    file->updatePreviewImage(newPixels);
}

OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT


text: Grupo de Pesquisa em Processamento e Análise de Neuroimagens Multimodais


text:
<?php

declare(strict_types=1);

namespace Hostnet\Component\EntityBlamable\Listener;

use Hostnet\Component\EntityBlamable\Blamable;
use Hostnet\Component\EntityTracker\Event\EntityChangedEvent;
use PHPUnit\Framework\TestCase;

/**
 * @covers \Hostnet\Component\EntityBlamable\Listener\BlamableListener
 */
class BlamableListenerTest extends TestCase
{
    private $em;
    private $resolver;
    private $provider;
    private $entity;
    private $uow;

    public function setUp(): void
    {
        $this->em       = $this->createMock('Doctrine\ORM\EntityManagerInterface');
        $this->resolver = $this->createMock('Hostnet\Component\EntityBlamable\Resolver\BlamableResolverInterface');
        $this->provider = $this->createMock('Hostnet\Component\EntityBlamable\Provider\BlamableProviderInterface');
        $this->entity   = $this->createMock('Hostnet\Component\EntityBlamable\BlamableInterface');
    }

    public function testOnEntityChangedNoInterface(): void
    {
        $this->provider
            ->expects($this->never())
            ->method('getChangedAt');

        $event    = new EntityChangedEvent($this->em, new \stdClass(), new \stdClass(), []);
        $listener = new BlamableListener($this->resolver, $this->provider);
        $listener->entityChanged($event);
    }

    public function testOnEntityChangedExistingEntity(): void
    {
        $at = new \DateTime();
        $by = 'henk';

        $this->provider
            ->expects($this->once())
            ->method('getChangedAt')
            ->willReturn($at);

        $this->provider
            ->expects($this->once())
            ->method('getUpdatedBy')
            ->willReturn($by);

        $this->entity
            ->expects($this->once())
            ->method('setUpdatedAt')
            ->with($at);

        $this->entity
            ->expects($this->once())
            ->method('setUpdatedBy')
            ->with($by);

        $this->resolver
            ->expects($this->once())
            ->method('getBlamableAnnotation')
            ->willReturn(new Blamable());

        $event    = new EntityChangedEvent($this->em, $this->entity, new \stdClass(), []);
        $listener = new BlamableListener($this->resolver, $this->provider);
        $listener->entityChanged($event);
    }

    public function testOnEntityChangedNewEntity(): void
    {
        $at = new \DateTime();
        $by = 'henk';

        $this->provider
            ->expects($this->once())
            ->method('getChangedAt')
            ->willReturn($at);

        $this->provider
            ->expects($this->once())
            ->method('getUpdatedBy')
            ->willReturn($by);

        $this->entity
            ->expects($this->once())
            ->method('setUpdatedAt')
            ->with($at);

        $this->entity
            ->expects($this->once())
            ->method('setCreatedAt')
            ->with($at);

        $this->entity
            ->expects($this->once())
            ->method('setUpdatedBy')
            ->with($by);

        $this->resolver
            ->expects($this->once())
            ->method('getBlamableAnnotation')
            ->willReturn(new Blamable());

        $event    = new EntityChangedEvent($this->em, $this->entity, null, []);
        $listener = new BlamableListener($this->resolver, $this->provider);
        $listener->entityChanged($event);
    }
}


text:
import re
import os
import setuptools

def match(x):
    # ignore comments
    if re.search(r'(^\s*#)', x):
        return False
    return True

def replace(x):
    match_replace = re.search(r'egg=(.*)', x)
    if match_replace:
        return match_replace.group(1)
    return x

def find_templates(path, parent=None, include_dir=False):
    results = []

    if parent is None:
        parent = []
    else:
        parent = parent.copy()
    parent.append(path)

    for possible_dir in os.listdir('/'.join(parent)):
        possible_path = '/'.join(parent + [possible_dir])

        if include_dir and os.path.isfile(possible_path):
            results.append(possible_path)
            continue

        if not os.path.isdir(possible_path):
            continue

        if possible_dir in ['templates','static'] and parent[-1] in ['blueprint', 'api']:
            results += find_templates(possible_dir, parent, True)
        else:
            results += find_templates(possible_dir, parent, include_dir)

    return results

with open('requirements.txt') as f:
    required = [replace(x) for x in f.read().splitlines()
                if match(x)]

with open('VERSION') as f:
    version = f.read().strip()

def get_sugarcoat_data():
    result = []
    for data_dir in find_templates('sugarcoat'):
        if data_dir.index('sugarcoat/') == 0:
            data_dir = data_dir[10:]
        result.append(data_dir)
    return result

setuptools.setup(
    name='sugarcoat',
    version=version,
    description='Sugarcoat',
    long_description='Easier to consume APIs.',
    author='Brian Price',
    author_email='brian.price@badcure.com',
    url='https://github.com/badcure/sugarcoat/',
    packages=setuptools.find_packages() + ['sugarcoat.api.templates'],
    include_package_data=True,
    package_data={'sugarcoat': get_sugarcoat_data() },
    zip_safe=False,
    install_requires=required,
)


text:
$content = 'C:\Projects\Guard\NuGet_Src\content'

if ((Test-Path -path $content))
{
	Remove-Item -Recurse -Force $content
}
New-Item -Path $content -type directory

Copy-Item C:\Projects\Guard\CodeGuard\ $content -recurse -verbose -filter "*.cs"

Get-ChildItem -Recurse | Where-Object {$_.Name -match '.cs'} | Rename-Item -NewName { $_.Name -replace '.cs','.cs.pp' }

$old = 'Seterlund.'
$new = '$rootnamespace$.'

Get-ChildItem $content -Recurse | Where {$_ -IS [IO.FileInfo]} |

% {

(Get-Content $_.FullName) -replace $old,$new | Set-Content $_.FullName

Write-Host "Processed: " + $_.FullName

}


text:
import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import moment from 'moment';

import eng2cht from '../../utils/eng2cht';
import position2color from '../../utils/position2color';

class Record extends Component {
  static propTypes = {
    activeRecord: PropTypes.object,
    data: PropTypes.object.isRequired,
    setToActiveRecord: PropTypes.func.isRequired

  }

  render() {
    const styles = require('./PositionPartyGroup.scss');
    const {data, activeRecord, setToActiveRecord, resetActiveRecord} = this.props;

    let date = moment.unix(data.date);
    let cubeActiveStyle = "";

    //是否為黨團
    let isCaucus = (data.legislator.indexOf("黨團")!== -1);
    let caucusStyle = isCaucus ? styles.caucus : "";

    if(activeRecord.id === data.id)
       cubeActiveStyle = styles.positionCubeActive;

    /* active record */
    let detailText;
    if((activeRecord.id === data.id)){
          let date = moment.unix(activeRecord.date);

          let preview = (activeRecord.content.length > 40) ? activeRecord.content.slice(0,40)+"..." : activeRecord.content;
          detailText =  (

              <Link to={`/records/${activeRecord.id}`} className={styles.activeCube}>

{date.format('YYYY-MM-DD')} / {activeRecord.legislator} / {activeRecord.meetingCategory}

{preview}

              </Link>

);
    }

    return (

          {detailText}

          <Link to={`/records/${data.id}`}
                className={` ${styles.positionCube} ${cubeActiveStyle} ${styles[data.party]} ${caucusStyle} `}
                onMouseEnter={setToActiveRecord.bind(null, data)}
                onMouseLeave={resetActiveRecord.bind(null)} >
          </Link>

    )
  }

  props = {
    className: ''
  }
}

export default class PositionPartyGroup extends Component {
  static propTypes = {
    data: PropTypes.object.isRequired,
    issueStatement: PropTypes.string.isRequired,
    activeRecord: PropTypes.array,
    setToActiveRecord: PropTypes.func.isRequired

  }

  render() {
    const styles = require('./PositionPartyGroup.scss');
    const {data, issueStatement, activeRecord, setToActiveRecord, resetActiveRecord} = this.props;

    /* 這裡是一筆一筆的資料,方框顏色表示立場 */
    let records = data.records.map((item,index)=>{
      return <Record data={item} key={index}
                     setToActiveRecord={setToActiveRecord}
                     activeRecord={activeRecord}
                     resetActiveRecord={resetActiveRecord} />
    });

    /* 計算外面的圓圈大小,跟裡面框框集合的寬度 */

    // 寬度是 record 數=> 開根號,round up 到整數
    // $cubeSize: 20px
    let width = Math.ceil(Math.sqrt(records.length))*20;

    // 外面是一個兩倍大的 div,然後做圓弧
    // boder 目前是 ad-hoc 的兩種寬度,需要再調整
    let borderWidth = (width>140)? 6:4;

    // 依照不同的立場設定框框的顏色
    let cubesWrap = {
      width: width * 2,
      height: width * 2,
      boxShadow: `0px 0px 0px ${borderWidth}px ${position2color(data.position)}`,
      borderRadius: "50%",
      display: "inline-block",
      verticalAlign: "middle",
      position: "relative",
      margin: "20px 20px"
    }

    // 依照紀錄筆數,設定內圈的寬度
    let cubes = {
      width: width,
      height: width,
      position: "absolute",
      top: width/2,
      left: width/2
    }

    let title = `我${eng2cht(data.position)}${issueStatement}`;
    if(data.position === "unknown")
      title = "我立場模糊";

    return (

{title}

{records}

    );
  }

  props = {
    className: ''
  }
}


text:
export const COMMENT_TYPE_ARTICLE = 1;
export const COMMENT_TYPE_PHOTO = 2;


text:
package ltm

import (
	"strings"

	"github.com/e-XpertSolutions/f5-rest-client/f5"
)

type ProfileClientSSLList struct {
	Items    []ProfileClientSSL `json:"items,omitempty"`
	Kind     string             `json:"kind,omitempty" pretty:",expanded"`
	SelfLink string             `json:"selflink,omitempty" pretty:",expanded"`
}

// TMOptions is a slice of strings. We define it as it's own type so that we can handle the JSON marshalling in a custom
// way. When the API returns the TMOptions, it does so as a string wrapped in { }. However, when posting back to the API,
// an array of strings is expected.
type TMOptions []string

// UnmarshalJSON converts a byte stream into a populated TMOptions slice
func (tm *TMOptions) UnmarshalJSON(data []byte) error {
	// "{ dont-insert-empty-fragments no-tlsv1.3 }"
	asString := string(data)

	asString = strings.ReplaceAll(asString, "\"", "")
	asString = strings.TrimSpace(asString)
	asString = strings.TrimPrefix(asString, "{")
	asString = strings.TrimSuffix(asString, "}")
	asString = strings.TrimSpace(asString)

	*tm = strings.Split(asString, " ")
	return nil
}

type ProfileClientSSL struct {
	AlertTimeout             string   `json:"alertTimeout,omitempty"`
	AllowDynamicRecordSizing string   `json:"allowDynamicRecordSizing,omitempty"`
	AllowExpiredCRL          string   `json:"allowExpiredCrl,omitempty"`
	AllowNonSSL              string   `json:"allowNonSsl,omitempty"`
	AppService               string   `json:"appService,omitempty"`
	Authenticate             string   `json:"authenticate,omitempty"`
	AuthenticateDepth        int      `json:"authenticateDepth,omitempty"`
	BypassOnClientCertFail   string   `json:"bypassOnClientCertFail,omitempty"`
	BypassOnHandshakeAlert   string   `json:"bypassOnHandshakeAlert,omitempty"`
	CAFile                   string   `json:"caFile,omitempty"`
	CacheSize                int      `json:"cacheSize,omitempty"`
	CacheTimeout             int      `json:"cacheTimeout,omitempty"`
	Cert                     string   `json:"cert,omitempty"`
	CertExtensionIncludes    []string `json:"certExtensionIncludes,omitempty"`
	CertKeyChain             []struct {
		AppService    string `json:"appService,omitempty"`
		Cert          string `json:"cert,omitempty"`
		CertReference struct {
			Link string `json:"link,omitempty"`
		} `json:"certReference,omitempty"`
		Chain        string `json:"chain,omitempty"`
		Key          string `json:"key,omitempty"`
		KeyReference struct {
			Link string `json:"link,omitempty"`
		} `json:"keyReference,omitempty"`
		Name string `json:"name,omitempty"`
	} `json:"certKeyChain,omitempty"`
	CertLifespan           int    `json:"certLifespan,omitempty"`
	CertLookupByIpaddrPort string `json:"certLookupByIpaddrPort,omitempty"`
	CertReference          struct {
		Link string `json:"link,omitempty"`
	} `json:"certReference,omitempty"`
	Chain            string `json:"chain,omitempty"`
	CipherGroup      string `json:"cipherGroup,omitempty"`
	Ciphers          string `json:"ciphers,omitempty"`
	ClientCertCA     string `json:"clientCertCa,omitempty"`
	CRLFile          string `json:"crlFile,omitempty"`
	CRLFileReference struct {
		Link string `json:"link,omitempty"`
	} `json:"crlFileReference,omitempty"`
	DefaultsFrom                    string `json:"defaultsFrom,omitempty"`
	Description                     string `json:"description,omitempty"`
	DestinationIPBlacklist          string `json:"destinationIpBlacklist,omitempty"`
	DestinationIPWhitelist          string `json:"destinationIpWhitelist,omitempty"`
	ForwardProxyBypassDefaultAction string `json:"forwardProxyBypassDefaultAction,omitempty"`
	FullPath                        string `json:"fullPath,omitempty"`
	Generation                      int    `json:"generation,omitempty"`
	GenericAlert                    string `json:"genericAlert,omitempty"`
	HandshakeTimeout                string `json:"handshakeTimeout,omitempty"`
	HostnameBlacklist               string `json:"hostnameBlacklist,omitempty"`
	HostnameWhitelist               string `json:"hostnameWhitelist,omitempty"`
	InheritCertkeychain             string `json:"inheritCertkeychain,omitempty"`
	Key                             string `json:"key,omitempty"`
	KeyReference                    struct {
		Link string `json:"link,omitempty"`
	} `json:"keyReference,omitempty"`
	Kind                               string    `json:"kind,omitempty"`
	MaxActiveHandshakes                string    `json:"maxActiveHandshakes,omitempty"`
	MaxAggregateRenegotiationPerMinute string    `json:"maxAggregateRenegotiationPerMinute,omitempty"`
	MaxRenegotiationsPerMinute         int       `json:"maxRenegotiationsPerMinute,omitempty"`
	MaximumRecordSize                  int       `json:"maximumRecordSize,omitempty"`
	ModSslMethods                      string    `json:"modSslMethods,omitempty"`
	Mode                               string    `json:"mode,omitempty"`
	Name                               string    `json:"name,omitempty"`
	NotifyCertStatusToVirtualServer    string    `json:"notifyCertStatusToVirtualServer,omitempty"`
	OCSPStapling                       string    `json:"ocspStapling,omitempty"`
	Partition                          string    `json:"partition,omitempty"`
	PeerCertMode                       string    `json:"peerCertMode,omitempty"`
	PeerNoRenegotiateTimeout           string    `json:"peerNoRenegotiateTimeout,omitempty"`
	ProxyCACert                        string    `json:"proxyCaCert,omitempty"`
	ProxyCAKey                         string    `json:"proxyCaKey,omitempty"`
	ProxySSL                           string    `json:"proxySsl,omitempty"`
	ProxySSLPassthrough                string    `json:"proxySslPassthrough,omitempty"`
	RenegotiateMaxRecordDelay          string    `json:"renegotiateMaxRecordDelay,omitempty"`
	RenegotiatePeriod                  string    `json:"renegotiatePeriod,omitempty"`
	RenegotiateSize                    string    `json:"renegotiateSize,omitempty"`
	Renegotiation                      string    `json:"renegotiation,omitempty"`
	RetainCertificate                  string    `json:"retainCertificate,omitempty"`
	SecureRenegotiation                string    `json:"secureRenegotiation,omitempty"`
	SelfLink                           string    `json:"selfLink,omitempty"`
	ServerName                         string    `json:"serverName,omitempty"`
	SessionMirroring                   string    `json:"sessionMirroring,omitempty"`
	SessionTicket                      string    `json:"sessionTicket,omitempty"`
	SessionTicketTimeout               int       `json:"sessionTicketTimeout,omitempty"`
	SNIDefault                         string    `json:"sniDefault,omitempty"`
	SNIRequire                         string    `json:"sniRequire,omitempty"`
	SourceIPBlacklist                  string    `json:"sourceIpBlacklist,omitempty"`
	SourceIPWhitelist                  string    `json:"sourceIpWhitelist,omitempty"`
	SSLForwardProxy                    string    `json:"sslForwardProxy,omitempty"`
	SSLForwardProxyBypass              string    `json:"sslForwardProxyBypass,omitempty"`
	SSLSignHash                        string    `json:"sslSignHash,omitempty"`
	StrictResume                       string    `json:"strictResume,omitempty"`
	TMOptions                          TMOptions `json:"tmOptions,omitempty"`
	UncleanShutdown                    string    `json:"uncleanShutdown,omitempty"`
}

const ProfileClientSSLEndpoint = "/profile/client-ssl"

type ProfileClientSSLResource struct {
	c *f5.Client
}

func (r *ProfileClientSSLResource) ListAll() (*ProfileClientSSLList, error) {
	var list ProfileClientSSLList
	if err := r.c.ReadQuery(BasePath+ProfileClientSSLEndpoint, &list); err != nil {
		return nil, err
	}
	return &list, nil
}

func (r *ProfileClientSSLResource) Get(id string) (*ProfileClientSSL, error) {
	var item ProfileClientSSL
	if err := r.c.ReadQuery(BasePath+ProfileClientSSLEndpoint+"/"+id, &item); err != nil {
		return nil, err
	}
	return &item, nil
}

func (r *ProfileClientSSLResource) Create(item ProfileClientSSL) error {
	if err := r.c.ModQuery("POST", BasePath+ProfileClientSSLEndpoint, item); err != nil {
		return err
	}
	return nil
}

func (r *ProfileClientSSLResource) Edit(id string, item ProfileClientSSL) error {
	if err := r.c.ModQuery("PATCH", BasePath+ProfileClientSSLEndpoint+"/"+id, item); err != nil {
		return err
	}
	return nil
}

func (r *ProfileClientSSLResource) Delete(id string) error {
	if err := r.c.ModQuery("DELETE", BasePath+ProfileClientSSLEndpoint+"/"+id, nil); err != nil {
		return err
	}
	return nil
}