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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>energy.usef</groupId>
		<artifactId>usef-workflow</artifactId>
		<version>1.3.6</version>
	</parent>
	<artifactId>usef-cro</artifactId>
	<packaging>jar</packaging>
	<dependencies>
		<dependency>
			<groupId>energy.usef</groupId>
			<artifactId>usef-core-transport</artifactId>
			<version>1.3.6</version>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>com.github.fge</groupId>
			<artifactId>json-schema-validator</artifactId>
			<version>2.2.6</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>3.0.8.Final</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson-provider</artifactId>
			<version>3.0.8.Final</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace BitPayAPI
{
    /// <summary>
    /// Based on BitPay API v0.3.1 - https://bitpay.com/downloads/bitpayApi.pdf
    /// Bitcoin: 1qQSVhPa3ivWCefGp6ZjjSjHUpGUnhiL1
    /// </summary>
    public class BitPay
    {
        public string APIKey { get; set; }
        public string BaseURL { get; set; }
        public string CreateInvoiceURL { get; set; }
        public string GetInvoiceURL { get; set; }
        public string GetRatesURL { get; set; }

        public BitPay(string apiKey)
        {
            APIKey = apiKey;
            BaseURL = "https://bitpay.com/api";
            CreateInvoiceURL = "/invoice";
            GetInvoiceURL = "/invoice/";
            GetRatesURL = "/rates";
        }

        public InvoiceResponse CreateInvoice(InvoiceRequest request, Log log)
        {
            if (request.Price <= 0)
                throw new Exception("Price must be greater than zero.");

            if (String.IsNullOrEmpty(request.Currency))
                throw new Exception("Currency must be specified.");

            log.RequestURL = BaseURL + CreateInvoiceURL;
            log.RequestData = JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            log.ResponseData = PostJSON(log.RequestURL, log.RequestData, true);

            JObject obj = JObject.Parse(log.ResponseData);

            var errorObj = obj["error"];

            if (errorObj != null)
                return new InvoiceResponse() { ErrorType = errorObj["type"].ToString(), ErrorMessage = errorObj["message"].ToString() };

            return new InvoiceResponse() { Invoice = obj.ToObject<Invoice>() };
        }

        public InvoiceResponse GetInvoice(string invoiceId, Log log)
        {
            log.RequestURL = BaseURL + GetInvoiceURL + invoiceId;
            log.ResponseData = GetJSON(log.RequestURL, true);

            JObject obj = JObject.Parse(log.ResponseData);

            var errorObj = obj["error"];

            if (errorObj != null)
                return new InvoiceResponse() { ErrorType = errorObj["type"].ToString(), ErrorMessage = errorObj["message"].ToString() };

            return new InvoiceResponse() { Invoice = obj.ToObject<Invoice>() };
        }

        public static Invoice GetInvoiceFromJSON(string json)
        {
            return JsonConvert.DeserializeObject<Invoice>(json);
        }

        public List<ConversionRate> GetRates(Log log)
        {
            log.RequestURL = BaseURL + GetRatesURL;
            log.ResponseData = GetJSON(log.RequestURL, false);

            return JsonConvert.DeserializeObject<List<ConversionRate>>(log.ResponseData);
        }

        private string PostJSON(string url, string data, bool sendAPIKey)
        {
            using (WebClient wc = GetWebClient(sendAPIKey))
            {
                wc.Headers.Add("Content-Type", "application/json");

                return wc.UploadString(url, data);
            }
        }

        private string GetJSON(string url, bool sendAPIKey)
        {
            using (WebClient wc = GetWebClient(sendAPIKey))
            {
                return wc.DownloadString(url);
            }
        }

        private WebClient GetWebClient(bool sendAPIKey)
        {
            WebClient wc = new WebClient();

            if (sendAPIKey)
            {
                // setting WebClient.Credentials doesn't send the auth headers first time so force this manually
                wc.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(APIKey + ":"));
            }

            wc.Headers[HttpRequestHeader.UserAgent] = "BitPay WebForms (https://github.com/timabbott83/bitpay-webforms)";

            return wc;
        }
    }

    public class InvoiceRequest
    {
        [JsonProperty("price")]
        public decimal Price { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("postData")]
        public Dictionary<string, string> PosData { get; set; }

        [JsonProperty("notificationURL")]
        public string NotificationURL { get; set; }

        [JsonProperty("transactionSpeed")]
        public string TransactionSpeed { get; set; }

        [JsonProperty("fullNotifications")]
        public bool? FullNotifications { get; set; }

        [JsonProperty("notificationEmail")]
        public string NotifcationEmail { get; set; }

        [JsonProperty("redirectURL")]
        public string RedirectURL { get; set; }

        [JsonProperty("orderID")]
        public string OrderID { get; set; }

        [JsonProperty("itemDesc")]
        public string ItemDesc { get; set; }

        [JsonProperty("itemCode")]
        public string ItemCode { get; set; }

        [JsonProperty("physical")]
        public bool? Physical { get; set; }

        [JsonProperty("buyerName")]
        public string BuyerName { get; set; }

        [JsonProperty("buyerAddress1")]
        public string BuyerAddress1 { get; set; }

        [JsonProperty("buyerAddress2")]
        public string BuyerAddress2 { get; set; }

        [JsonProperty("buyerCity")]
        public string BuyerCity { get; set; }

        [JsonProperty("buyerState")]
        public string BuyerState { get; set; }

        [JsonProperty("buyerZip")]
        public string BuyerZip { get; set; }

        [JsonProperty("buyerCountry")]
        public string BuyerCountry { get; set; }

        [JsonProperty("buyerEmail")]
        public string BuyerEmail { get; set; }

        [JsonProperty("buyerPhone")]
        public string BuyerPhone { get; set; }

        public InvoiceRequest()
        {
        }
    }

    public class InvoiceResponse
    {
        public bool Success { get { return Invoice != null; } }
        public Invoice Invoice { get; set; }
        public string ErrorType { get; set; }
        public string ErrorMessage { get; set; }

        public InvoiceResponse()
        {
        }
    }

    public class Invoice
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("url")]
        public string URL { get; set; }

        [JsonProperty("posData")]
        public Dictionary<string, string> PosData { get; set; }

        [JsonProperty("status")]
        [JsonConverter(typeof(StringEnumConverter))]
        public InvoiceStatus Status { get; set; }

        [JsonProperty("price")]
        public decimal Price { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("btcPrice")]
        public decimal BTCPrice { get; set; }

        [JsonProperty("invoiceTime")]
        [JsonConverter(typeof(JsonDateTimeConverter))]
        public DateTime InvoiceTime { get; set; }

        [JsonProperty("expirationTime")]
        [JsonConverter(typeof(JsonDateTimeConverter))]
        public DateTime ExpirationTime { get; set; }

        [JsonProperty("currentTime")]
        [JsonConverter(typeof(JsonDateTimeConverter))]
        public DateTime CurrentTime { get; set; }

        public Invoice()
        {
        }
    }

    public enum InvoiceStatus
    {
        New,
        Paid,
        Confirmed,
        Complete,
        Expired,
        Invalid
    }

    public class Log
    {
        public string RequestURL { get; internal set; }
        public string RequestData { get; internal set; }
        public string ResponseData { get; internal set; }

        public Log()
        {
        }
    }

    public class ConversionRate
    {
        [JsonProperty("code")]
        public string CurrencyCode { get; set; }

        [JsonProperty("name")]
        public string CurrencyName { get; set; }

        [JsonProperty("rate")]
        public decimal Rate { get; set; }

        public ConversionRate()
        {
        }
    }

    public class JsonDateTimeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(reader.Value));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //throw new NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Plotting
--------
Plotting functions collections for exploring new data.

"""
from catdistrib_plot import barplot_plot
from contdistrib_plot import cont_distrib_plot
from geo_plotting import plot_in_map
from temp_plotting import temp_distrib, distrib_across_temp

def general_plot(df, info_var):
    """General plotting function. That function wrappes all the plotting
    functions of the module in order to make easy to automatize some process
    of exploring new data.

    Parameters
    ----------
    df: pd.DataFrame
        the data to explore.
    info_var: dict
        the information to plot the variables selected. The `info_var` is
        formed by:
            * type: the type of the variables we want to plot.
            * variables: the variables we want to plot.
            * logscale: if we want to use logarithmic scale.
            * hist_table
            * log_hist_table
            * agg_time

    Returns
    -------
    fig: matplotlib.pyplot.figure
        the figure of the plot defined by the info_var.

    """
    typevar = info_var['type'].lower()
    if typevar in ['discrete', 'categorical']:
        fig = barplot_plot(df[info_var['variables']])
        if info_var['logscale'] in [True, 'True', 'TRUE']:
            fig = [fig, barplot_plot(df[info_var['variables']], True)]
    elif typevar == 'continuous':
#        fig = cont_distrib_plot(info_var['count_hist'], info_var['n_bins'])
        fig = cont_distrib_plot(df[info_var['variables']],
                                info_var['hist_table'][1])
        if info_var['logscale'] in [True, 'True', 'TRUE']:
            fig = [fig, cont_distrib_plot(df[info_var['variables']],
                                          info_var['log_hist_table'][1], True)]
    elif typevar == 'coordinates':
        fig = plot_in_map(df[info_var['variables']])
    elif typevar in ['time', 'temporal']:
        fig = temp_distrib(df[info_var['variables']], info_var['agg_time'])
        if info_var['logscale'] in [True, 'True', 'TRUE']:
            fig = [fig, temp_distrib(df[info_var['variables']],
                                     info_var['agg_time'], True)]
    elif typevar == 'tmpdist':
        fig = distrib_across_temp(df, info_var['variables'])
        if info_var['logscale'] in [True, 'True', 'TRUE']:
            fig = [fig, distrib_across_temp(df, info_var['variables'],
                                            logscale=True)]
    else:
        print typevar, info_var['variables']

    #figures = {'figure': fig, 'plot_desc': info_var['plot_desc']}
    return fig


text:
import sys
import unittest

import numpy as np
import quantities as pq
from numpy.testing import assert_array_almost_equal

from elephant.parallel import SingleProcess, ProcessPoolExecutor
from elephant.spike_train_generation import homogeneous_poisson_process
from elephant.statistics import mean_firing_rate

python_version_major = sys.version_info.major

class TestParallel(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.executors_cls = [SingleProcess, ProcessPoolExecutor]
        try:
            from elephant.parallel.mpi import MPIPoolExecutor, MPICommExecutor
            cls.executors_cls.extend([MPIPoolExecutor, MPICommExecutor])
        except ImportError:
            # mpi4py is not installed
            pass

        np.random.seed(28)
        n_spiketrains = 10
        cls.spiketrains = tuple(
            homogeneous_poisson_process(
                rate=10 * pq.Hz, t_stop=10 * pq.s, as_array=True)
            for _ in range(n_spiketrains)
        )
        cls.mean_fr = tuple(map(mean_firing_rate, cls.spiketrains))

    @unittest.skipUnless(python_version_major == 3, "subTest requires 3.4")
    def test_mean_firing_rate(self):
        for executor_cls in self.executors_cls:
            with self.subTest(executor_cls=executor_cls):
                executor = executor_cls()
                mean_fr = executor.execute(handler=mean_firing_rate,
                                           args_iterate=self.spiketrains)
                assert_array_almost_equal(mean_fr, self.mean_fr)

if __name__ == '__main__':
    unittest.main()


text:
package com.mandrillapp.api.messages.common;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;

@JsonPropertyOrder({
	"name",
	"content"
})
public class NameContent {

	@JsonProperty("name")
	private String name;
	@JsonProperty("content")
	private String content;

	public NameContent(final String name, final String content) {
		this.name = name;
		this.content = content;
	}

	public String getName() {
		return name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public String getContent() {
		return content;
	}

	public void setContent(final String content) {
		this.content = content;
	}

}


text:
Subroutine color_palette(number_color,Color_matrix,color)
	use dflib
	integer::number_color,Color_matrix(4,8),color(1:256)
	integer(4),dimension(:),allocatable::Primary_color
	real(8)::red_step,green_step,blue_step,color_step
	allocate(primary_color(number_color))
	do i=1,number_color
		color(color_matrix(4,i))=rgbtointeger(color_matrix(1,i),color_matrix(2,i),color_matrix(3,i))
	end do
	i=1
	do while (i/=number_color)
		color_step=color_matrix(4,i+1)-color_matrix(4,i)
		red_step=(color_matrix(1,i+1)-color_matrix(1,i))/color_step
		green_step=(color_matrix(2,i+1)-color_matrix(2,i))/color_step
		blue_step=(color_matrix(3,i+1)-color_matrix(3,i))/color_step
		do j=color_matrix(4,i)+1,color_matrix(4,i+1)-1
			color(j)=rgbtointeger(int(color_matrix(1,i)+((j-color_matrix(4,i)+1)*red_step)),int(color_matrix(2,i)+((j-color_matrix(4,i)+1)*green_step)),int(color_matrix(3,i)+((j-color_matrix(4,i)+1)*blue_step)))
		end do
		i=i+1
	end do
end subroutine color_palette


text:
const url = require("url");

// scrape function
// res: `node-fetch` `Response` object (https://github.com/bitinn/node-fetch#interface-body)
// $:   `cheerio` object with page loaded (https://github.com/cheeriojs/cheerio#api)
// return: Promise of scraped result
module.exports = (res, $) => {
  // console.info("processing [%s] ...", res.url);

  // show off your cheerio-fu here
  return Promise.resolve({
    imgs: $("img")
      .toArray()
      .map(el => url.resolve(res.url, $(el).attr("src")))
  });
};


text:
package com.xqbase.tuna.cli;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.net.ssl.SSLContext;

import com.xqbase.tuna.Connection;
import com.xqbase.tuna.ConnectionFilter;
import com.xqbase.tuna.ConnectionSession;
import com.xqbase.tuna.Connector;
import com.xqbase.tuna.ConnectorImpl;
import com.xqbase.tuna.mux.EdgeServer;
import com.xqbase.tuna.mux.MuxContext;
import com.xqbase.tuna.ssl.SSLFilter;
import com.xqbase.tuna.util.TimeoutQueue;
import com.xqbase.util.Conf;
import com.xqbase.util.Log;
import com.xqbase.util.Numbers;
import com.xqbase.util.Service;
import com.xqbase.util.Time;

class EdgeLoop implements Runnable {
	private static SSLContext sslc;

	static {
		try {
			sslc = SSLContexts.get(null, 0);
		} catch (IOException | GeneralSecurityException e) {
			throw new RuntimeException(e);
		}
	}

	Connector.Closeable closeable = null;
	EdgeServer edge = null;
	ConnectorImpl connector;
	int port;

	private String muxHost;
	private int muxPort, queueLimit, logLevel;
	private boolean ssl;
	private byte[] authPhrase;

	EdgeLoop(ConnectorImpl connector, int port, String muxHost, int muxPort,
			boolean ssl, byte[] authPhrase, int queueLimit, int logLevel) {
		this.connector = connector;
		this.port = port;
		this.muxHost = muxHost;
		this.muxPort = muxPort;
		this.ssl = ssl;
		this.authPhrase = authPhrase;
		this.queueLimit = queueLimit;
		this.logLevel = logLevel;
	}

	@Override
	public void run() {
		MuxContext context = new MuxContext(connector, t -> {
			Log.w("Authentication Failed");
			if (edge == null) {
				return false;
			}
			Log.i("Disconnect Mux and wait 1 second before retry ...");
			if (closeable != null) {
				closeable.close();
				closeable = null;
			}
			edge.disconnect();
			edge = null;
			connector.postDelayed(EdgeLoop.this, Time.SECOND);
			return false;
		}, queueLimit, logLevel);
		edge = new EdgeServer(context, authPhrase);
		Connection connection = edge.getMuxConnection().appendFilter(new ConnectionFilter() {
			@Override
			public void onConnect(ConnectionSession session) {
				super.onConnect(session);
				try {
					closeable = connector.add(edge, port);
				} catch (IOException e) {
					Log.w(e.getMessage());
					if (edge == null) {
						return;
					}
					Log.i("Disconnect Mux and wait 1 second before retry ...");
					edge.disconnect();
					edge = null;
					connector.postDelayed(EdgeLoop.this, Time.SECOND);
				}
			}

			@Override
			public void onDisconnect() {
				super.onDisconnect();
				disconnect_();
			}

			@Override
			public void disconnect() {
				super.disconnect();
				disconnect_();
			}

			private void disconnect_() {
				if (closeable != null) {
					closeable.close();
					closeable = null;
				}
				if (edge == null) {
					return;
				}
				Log.i("Wait 1 second before retry ...");
				edge = null;
				connector.postDelayed(EdgeLoop.this, Time.SECOND);
			}
		});
		try {
			if (ssl) {
				TimeoutQueue<SSLFilter> ssltq = SSLFilter.getTimeoutQueue(60000);
				connector.scheduleDelayed(ssltq, 10000, 10000);
				connection = connection.appendFilter(new SSLFilter(connector,
						connector, ssltq, sslc, SSLFilter.CLIENT));
			}
			connector.connect(connection, muxHost, muxPort);
		} catch (IOException e) {
			Log.w("Edge Aborted: " + e.getMessage());
			connector.interrupt();
		}
	}
}

public class MuxEdge {
	private static final List<String> LOG_VALUE = Arrays.asList("debug", "verbose");

	private static Service service = new Service();

	public static void main(String[] args) {
		if (!service.startup(args)) {
			return;
		}
		if (args.length < 3) {
			System.out.println("MuxEdge Usage: java -cp tuna-tools.jar " +
					"com.xqbase.tuna.cli.MuxEdge <local-port> " +
					"<mux-host> <mux-port> [-s] [<auth-phrase>]");
			service.shutdown();
			return;
		}
		System.setProperty("java.util.logging.SimpleFormatter.format",
				"%1$tY-%1$tm-%1$td %1$tk:%1$tM:%1$tS.%1$tL %2$s%n%4$s: %5$s%6$s%n");
		Logger logger = Log.getAndSet(Conf.openLogger("MuxEdge.", 16777216, 10));

		int port = Numbers.parseInt(args[0], 80, 1, 65535);
		String muxHost = args[1];
		int muxPort = Numbers.parseInt(args[2], 8341, 1, 65535);
		boolean ssl = args.length > 3 && "-s".equalsIgnoreCase(args[3]);
		int i = ssl ? 4 : 3;
		byte[] authPhrase = (args.length <= i ||
				args[i] == null ? null : args[i].getBytes());
		Properties p = Conf.load("Mux");
		int queueLimit = Numbers.parseInt(p.getProperty("queue_limit"), 1048576);
		String logValue = Conf.DEBUG ? "verbose" : p.getProperty("log");
		int logLevel = logValue == null ? 0 :
				LOG_VALUE.indexOf(logValue.toLowerCase()) + 1;

		try (ConnectorImpl connector = new ConnectorImpl()) {
			service.register(connector::interrupt);
			new EdgeLoop(connector, port, muxHost, muxPort,
					ssl, authPhrase, queueLimit, logLevel).run();
			Log.i(String.format("MuxEdge Started (%s->%s:%s%s)",
					"" + port, muxHost, "" + muxPort, ssl ? "s" : ""));
			connector.doEvents();
		} catch (Error | RuntimeException e) {
			Log.e(e);
		}

		Log.i("Edge Stopped");
		Conf.closeLogger(Log.getAndSet(logger));
		service.shutdown();
	}
}


text:
<?php

namespace Morfeu\Bundle\BusinessBundle\Enum;

use Morfeu\Bundle\BusinessBundle\Enum\BaseEnum;

abstract class StatusPayment extends BaseEnum
{

    const FINISHED = 1;
    const DELETED = 0;
    const PENDING = 2;
    const PAID = 1;
    const NOT_PAID = 2;
    const ALL = -1;

}


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/colorspace.h"
#include "libavutil/eval.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "avfilter.h"
#include "drawutils.h"
#include "formats.h"
#include "internal.h"
#include "opencl.h"
#include "opencl_source.h"
#include "video.h"

static const char *const var_names[] = {
    "in_w",   "iw",
    "in_h",   "ih",
    "out_w",  "ow",
    "out_h",  "oh",
    "x",
    "y",
    "a",
    "sar",
    "dar",
    NULL
};

enum var_name {
    VAR_IN_W,   VAR_IW,
    VAR_IN_H,   VAR_IH,
    VAR_OUT_W,  VAR_OW,
    VAR_OUT_H,  VAR_OH,
    VAR_X,
    VAR_Y,
    VAR_A,
    VAR_SAR,
    VAR_DAR,
    VARS_NB
};

typedef struct PadOpenCLContext {
    OpenCLFilterContext ocf;
    int initialized;
    int is_rgb;
    int is_packed;
    int hsub, vsub;

    char *w_expr;
    char *h_expr;
    char *x_expr;
    char *y_expr;
    AVRational aspect;

    cl_command_queue command_queue;
    cl_kernel kernel_pad;

    int w, h;
    int x, y;
    uint8_t pad_rgba[4];
    uint8_t pad_color[4];
    cl_float4 pad_color_float;
    cl_int2 pad_pos;
} PadOpenCLContext;

static int pad_opencl_init(AVFilterContext *avctx, AVFrame *input_frame)
{
    PadOpenCLContext *ctx = avctx->priv;
    AVHWFramesContext *input_frames_ctx = (AVHWFramesContext *)input_frame->hw_frames_ctx->data;
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(input_frames_ctx->sw_format);
    uint8_t rgba_map[4];
    cl_int cle;
    int err;

    ff_fill_rgba_map(rgba_map, input_frames_ctx->sw_format);
    ctx->is_rgb = !!(desc->flags & AV_PIX_FMT_FLAG_RGB);
    ctx->is_packed = !(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
    ctx->hsub = desc->log2_chroma_w;
    ctx->vsub = desc->log2_chroma_h;

    err = ff_opencl_filter_load_program(avctx, &ff_opencl_source_pad, 1);
    if (err < 0)
        goto fail;

    ctx->command_queue = clCreateCommandQueue(
        ctx->ocf.hwctx->context,
        ctx->ocf.hwctx->device_id,
        0,
        &cle
    );

    if (ctx->is_rgb) {
        ctx->pad_color[rgba_map[0]] = ctx->pad_rgba[0];
        ctx->pad_color[rgba_map[1]] = ctx->pad_rgba[1];
        ctx->pad_color[rgba_map[2]] = ctx->pad_rgba[2];
        ctx->pad_color[rgba_map[3]] = ctx->pad_rgba[3];
    } else {
        ctx->pad_color[0] = RGB_TO_Y_BT709(ctx->pad_rgba[0], ctx->pad_rgba[1], ctx->pad_rgba[2]);
        ctx->pad_color[1] = RGB_TO_U_BT709(ctx->pad_rgba[0], ctx->pad_rgba[1], ctx->pad_rgba[2], 0);
        ctx->pad_color[2] = RGB_TO_V_BT709(ctx->pad_rgba[0], ctx->pad_rgba[1], ctx->pad_rgba[2], 0);
        ctx->pad_color[3] = ctx->pad_rgba[3];
    }

    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create OpenCL command queue %d.\n", cle);

    ctx->kernel_pad = clCreateKernel(ctx->ocf.program, "pad", &cle);
    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create pad kernel: %d.\n", cle);

    for (int i = 0; i < 4; ++i) {
        ctx->pad_color_float.s[i] = (float)ctx->pad_color[i] / 255.0;
    }

    ctx->pad_pos.s[0] = ctx->x;
    ctx->pad_pos.s[1] = ctx->y;

    ctx->initialized = 1;
    return 0;

fail:
    if (ctx->command_queue)
        clReleaseCommandQueue(ctx->command_queue);
    if (ctx->kernel_pad)
        clReleaseKernel(ctx->kernel_pad);
    return err;
}

static int filter_frame(AVFilterLink *link, AVFrame *input_frame)
{
    AVFilterContext *avctx = link->dst;
    AVFilterLink *outlink = avctx->outputs[0];
    PadOpenCLContext *pad_ctx = avctx->priv;
    AVFrame *output_frame = NULL;
    int err;
    cl_int cle;
    size_t global_work[2];
    cl_mem src, dst;

    if (!input_frame->hw_frames_ctx)
        return AVERROR(EINVAL);

    if (!pad_ctx->initialized) {
        err = pad_opencl_init(avctx, input_frame);
        if (err < 0)
            goto fail;
    }

    output_frame = ff_get_video_buffer(outlink, outlink->w, outlink->h);
    if (!output_frame) {
        err = AVERROR(ENOMEM);
        goto fail;
    }

    for (int p = 0; p < FF_ARRAY_ELEMS(output_frame->data); p++) {
        cl_float4 pad_color_float;
        cl_int2 pad_pos;

        if (pad_ctx->is_packed) {
            pad_color_float = pad_ctx->pad_color_float;
        } else {
            pad_color_float.s[0] = pad_ctx->pad_color_float.s[p];
            pad_color_float.s[1] = pad_ctx->pad_color_float.s[2];
        }

        if (p > 0 && p < 3) {
            pad_pos.s[0] = pad_ctx->pad_pos.s[0] >> pad_ctx->hsub;
            pad_pos.s[1] = pad_ctx->pad_pos.s[1] >> pad_ctx->vsub;
        } else {
            pad_pos.s[0] = pad_ctx->pad_pos.s[0];
            pad_pos.s[1] = pad_ctx->pad_pos.s[1];
        }

        src = (cl_mem)input_frame->data[p];
        dst = (cl_mem)output_frame->data[p];

        if (!dst)
            break;

        CL_SET_KERNEL_ARG(pad_ctx->kernel_pad, 0, cl_mem, &src);
        CL_SET_KERNEL_ARG(pad_ctx->kernel_pad, 1, cl_mem, &dst);
        CL_SET_KERNEL_ARG(pad_ctx->kernel_pad, 2, cl_float4, &pad_color_float);
        CL_SET_KERNEL_ARG(pad_ctx->kernel_pad, 3, cl_int2, &pad_pos);

        err = ff_opencl_filter_work_size_from_image(avctx, global_work, output_frame, p, 16);
        if (err < 0)
            goto fail;

        cle = clEnqueueNDRangeKernel(pad_ctx->command_queue, pad_ctx->kernel_pad, 2, NULL,
                                     global_work, NULL, 0, NULL, NULL);

        CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to enqueue pad kernel: %d.\n", cle);
    }

    // Run queued kernel
    cle = clFinish(pad_ctx->command_queue);
    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to finish command queue: %d.\n", cle);

    err = av_frame_copy_props(output_frame, input_frame);
    if (err < 0)
        goto fail;

    av_frame_free(&input_frame);

    return ff_filter_frame(outlink, output_frame);

fail:
    clFinish(pad_ctx->command_queue);
    av_frame_free(&input_frame);
    av_frame_free(&output_frame);
    return err;
}

static av_cold void pad_opencl_uninit(AVFilterContext *avctx)
{
    PadOpenCLContext *ctx = avctx->priv;
    cl_int cle;

    if (ctx->kernel_pad) {
        cle = clReleaseKernel(ctx->kernel_pad);
        if (cle != CL_SUCCESS)
            av_log(avctx, AV_LOG_ERROR, "Failed to release "
                   "kernel: %d.\n", cle);
    }

    if (ctx->command_queue) {
        cle = clReleaseCommandQueue(ctx->command_queue);
        if (cle != CL_SUCCESS)
            av_log(avctx, AV_LOG_ERROR, "Failed to release "
                   "command queue: %d.\n", cle);
    }

    ff_opencl_filter_uninit(avctx);
}

static int pad_opencl_config_output(AVFilterLink *outlink)
{
    AVFilterContext *avctx = outlink->src;
    AVFilterLink *inlink = avctx->inputs[0];
    PadOpenCLContext *ctx = avctx->priv;
    AVRational adjusted_aspect = ctx->aspect;
    double var_values[VARS_NB], res;
    int err, ret;
    char *expr;

    var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
    var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
    var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
    var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
    var_values[VAR_A]     = (double) inlink->w / inlink->h;
    var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
    var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];

    av_expr_parse_and_eval(&res, (expr = ctx->w_expr),
                           var_names, var_values,
                           NULL, NULL, NULL, NULL, NULL, 0, ctx);
    ctx->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
    if ((ret = av_expr_parse_and_eval(&res, (expr = ctx->h_expr),
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        return ret;
    ctx->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
    if (!ctx->h)
        var_values[VAR_OUT_H] = var_values[VAR_OH] = ctx->h = inlink->h;

    /* evaluate the width again, as it may depend on the evaluated output height */
    if ((ret = av_expr_parse_and_eval(&res, (expr = ctx->w_expr),
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        return ret;
    ctx->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
    if (!ctx->w)
        var_values[VAR_OUT_W] = var_values[VAR_OW] = ctx->w = inlink->w;

    if (adjusted_aspect.num && adjusted_aspect.den) {
        adjusted_aspect = av_div_q(adjusted_aspect, inlink->sample_aspect_ratio);
        if (ctx->h < av_rescale(ctx->w, adjusted_aspect.den, adjusted_aspect.num)) {
            ctx->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = av_rescale(ctx->w, adjusted_aspect.den, adjusted_aspect.num);
        } else {
            ctx->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = av_rescale(ctx->h, adjusted_aspect.num, adjusted_aspect.den);
        }
    }

    /* evaluate x and y */
    av_expr_parse_and_eval(&res, (expr = ctx->x_expr),
                           var_names, var_values,
                           NULL, NULL, NULL, NULL, NULL, 0, ctx);
    ctx->x = var_values[VAR_X] = res;
    if ((ret = av_expr_parse_and_eval(&res, (expr = ctx->y_expr),
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        return ret;
    ctx->y = var_values[VAR_Y] = res;
    /* evaluate x again, as it may depend on the evaluated y value */
    if ((ret = av_expr_parse_and_eval(&res, (expr = ctx->x_expr),
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        return ret;
    ctx->x = var_values[VAR_X] = res;

    if (ctx->x < 0 || ctx->x + inlink->w > ctx->w)
        ctx->x = var_values[VAR_X] = (ctx->w - inlink->w) / 2;
    if (ctx->y < 0 || ctx->y + inlink->h > ctx->h)
        ctx->y = var_values[VAR_Y] = (ctx->h - inlink->h) / 2;

    /* sanity check params */
    if (ctx->w < inlink->w || ctx->h < inlink->h) {
        av_log(ctx, AV_LOG_ERROR, "Padded dimensions cannot be smaller than input dimensions.\n");
        return AVERROR(EINVAL);
    }

    if (ctx->w > avctx->inputs[0]->w) {
        ctx->ocf.output_width  = ctx->w;
    } else {
        ctx->ocf.output_width  = avctx->inputs[0]->w;
    }

    if (ctx->h > avctx->inputs[0]->h) {
        ctx->ocf.output_height = ctx->h;
    } else {
        ctx->ocf.output_height = avctx->inputs[0]->h;
    }

    if (ctx->x + avctx->inputs[0]->w > ctx->ocf.output_width ||
        ctx->y + avctx->inputs[0]->h > ctx->ocf.output_height) {
        return AVERROR(EINVAL);
    }

    err = ff_opencl_filter_config_output(outlink);
    if (err < 0)
        return err;

    return 0;
}

static const AVFilterPad pad_opencl_inputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
        .filter_frame = filter_frame,
        .config_props = &ff_opencl_filter_config_input,
    },
    { NULL }
};

static const AVFilterPad pad_opencl_outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
        .config_props = &pad_opencl_config_output,
    },
    { NULL }
};

#define OFFSET(x) offsetof(PadOpenCLContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM

static const AVOption pad_opencl_options[] = {
    { "width",  "set the pad area width",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, FLAGS },
    { "w",      "set the pad area width",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, FLAGS },
    { "height", "set the pad area height",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, FLAGS },
    { "h",      "set the pad area height",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, FLAGS },
    { "x",      "set the x offset for the input image position", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, 0, INT16_MAX, FLAGS },
    { "y",      "set the y offset for the input image position", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, 0, INT16_MAX, FLAGS },
    { "color", "set the color of the padded area border", OFFSET(pad_rgba), AV_OPT_TYPE_COLOR, { .str = "black" }, 0, 0, FLAGS },
    { "aspect",  "pad to fit an aspect instead of a resolution", OFFSET(aspect), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, INT16_MAX, FLAGS },
    { NULL }
};

AVFILTER_DEFINE_CLASS(pad_opencl);

AVFilter ff_vf_pad_opencl = {
    .name           = "pad_opencl",
    .description    = NULL_IF_CONFIG_SMALL("Pad the input video."),
    .priv_size      = sizeof(PadOpenCLContext),
    .priv_class     = &pad_opencl_class,
    .init           = &ff_opencl_filter_init,
    .uninit         = &pad_opencl_uninit,
    .query_formats  = &ff_opencl_filter_query_formats,
    .inputs         = pad_opencl_inputs,
    .outputs        = pad_opencl_outputs,
    .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE
};


text:
package com.microsoft.azure.management.logic.v2018_07_01_preview.implementation;

import org.joda.time.DateTime;
import com.microsoft.azure.management.logic.v2018_07_01_preview.KeyVaultKeyReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;

/**
 * The integration account certificate.
 */
@JsonFlatten
@SkipParentValidation
public class IntegrationAccountCertificateInner extends Resource {
    /**
     * The created time.
     */
    @JsonProperty(value = "properties.createdTime", access = JsonProperty.Access.WRITE_ONLY)
    private DateTime createdTime;

    /**
     * The changed time.
     */
    @JsonProperty(value = "properties.changedTime", access = JsonProperty.Access.WRITE_ONLY)
    private DateTime changedTime;

    /**
     * The metadata.
     */
    @JsonProperty(value = "properties.metadata")
    private Object metadata;

    /**
     * The key details in the key vault.
     */
    @JsonProperty(value = "properties.key")
    private KeyVaultKeyReference key;

    /**
     * The public certificate.
     */
    @JsonProperty(value = "properties.publicCertificate")
    private String publicCertificate;

    /**
     * Get the created time.
     *
     * @return the createdTime value
     */
    public DateTime createdTime() {
        return this.createdTime;
    }

    /**
     * Get the changed time.
     *
     * @return the changedTime value
     */
    public DateTime changedTime() {
        return this.changedTime;
    }

    /**
     * Get the metadata.
     *
     * @return the metadata value
     */
    public Object metadata() {
        return this.metadata;
    }

    /**
     * Set the metadata.
     *
     * @param metadata the metadata value to set
     * @return the IntegrationAccountCertificateInner object itself.
     */
    public IntegrationAccountCertificateInner withMetadata(Object metadata) {
        this.metadata = metadata;
        return this;
    }

    /**
     * Get the key details in the key vault.
     *
     * @return the key value
     */
    public KeyVaultKeyReference key() {
        return this.key;
    }

    /**
     * Set the key details in the key vault.
     *
     * @param key the key value to set
     * @return the IntegrationAccountCertificateInner object itself.
     */
    public IntegrationAccountCertificateInner withKey(KeyVaultKeyReference key) {
        this.key = key;
        return this;
    }

    /**
     * Get the public certificate.
     *
     * @return the publicCertificate value
     */
    public String publicCertificate() {
        return this.publicCertificate;
    }

    /**
     * Set the public certificate.
     *
     * @param publicCertificate the publicCertificate value to set
     * @return the IntegrationAccountCertificateInner object itself.
     */
    public IntegrationAccountCertificateInner withPublicCertificate(String publicCertificate) {
        this.publicCertificate = publicCertificate;
        return this;
    }

}


text:
<?php
if ( ! function_exists('renderDataAttributes')) {
    function renderDataAttributes($attributes)
    {
        $mapped = [ ];
        foreach ($attributes as $key => $value) {
            $mapped[] = 'data-' . $key . '="' . $value . '"';
        };

        return implode(' ', $mapped);
    }
}
?>
@if(!empty($options))

@endif

<div class="g-recaptcha" data-sitekey="{{ $public_key }}" <?=renderDataAttributes($dataParams)?>>

        <textarea id="g-recaptcha-response" name="g-recaptcha-response"
                  class="g-recaptcha-response"
                  style="width: 250px; height: 80px; border: 1px solid #c1c1c1;
                         margin: 0; padding: 0; resize: none;">
        </textarea>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BorderUIResource.CompoundBorderUIResource (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.swing.plaf.BorderUIResource.CompoundBorderUIResource class">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing.plaf

Class BorderUIResource.CompoundBorderUIResource

java.lang.Object

javax.swing.border.AbstractBorder

javax.swing.border.CompoundBorder

javax.swing.plaf.BorderUIResource.CompoundBorderUIResource

All Implemented Interfaces:

Serializable, Border, UIResource

Enclosing class:

BorderUIResource

public static class BorderUIResource.CompoundBorderUIResource
extends CompoundBorder
implements UIResource

Field Summary

Fields inherited from class javax.swing.border.CompoundBorder

insideBorder, outsideBorder

Constructor Summary

Constructors

Constructor and Description

CompoundBorderUIResource(Border outsideBorder,
                        Border insideBorder)

Method Summary

Methods inherited from class javax.swing.border.CompoundBorder

getBorderInsets, getInsideBorder, getOutsideBorder, isBorderOpaque, paintBorder

Methods inherited from class javax.swing.border.AbstractBorder

getBaseline, getBaselineResizeBehavior, getBorderInsets, getInteriorRectangle, getInteriorRectangle

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CompoundBorderUIResource

@ConstructorProperties(value={"outsideBorder","insideBorder"})
public CompoundBorderUIResource(Border outsideBorder,
                                                                                Border insideBorder)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
/* SPDX-License-Identifier: BSD-2-Clause */

#pragma once
#include <tilck/kernel/fs/vfs_base.h>

#define KOBJ_BASE_FIELDS                    \
   REF_COUNTED_OBJECT;                      \
   void (*on_handle_close)(fs_handle h);    \
   void (*on_handle_dup)(fs_handle h);      \
   void (*destory_obj)(struct kobj_base *);

struct kobj_base {

   KOBJ_BASE_FIELDS
};

struct kfs_handle {

   FS_HANDLE_BASE_FIELDS
   struct kobj_base *kobj;
};

STATIC_ASSERT(sizeof(struct kfs_handle) <= MAX_FS_HANDLE_SIZE);

void init_kernelfs(void);
void kfs_destroy_handle(struct kfs_handle *h);
struct kfs_handle *
kfs_create_new_handle(const struct file_ops *fops,
                      struct kobj_base *kobj,
                      int fl_flags);


text:
<link href="./projects.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 Snake

 Use the arrow keys to move the snake around to eat food! Be careful, if you eat your tail, the game ends.

Play this demo in full screen.

 1) Create a "head" to control. Make the head move at a constant rate, and make it turn left and right when the left and right arrow keys are pressed.

Play this demo in full screen.

 2) Create "food" for your snake to eat. Have the food be created at a constant rate and appear at random points on the screen.

Play this demo in full screen.

3) Create a scoreboard. Whenever the snake touches a food sprite, have the food sprite disappear, and make the score increase.

Play this demo in full screen.

4) Make it so that each time the snake eats food, the snake's tail grows longer. Have the snake's tail trail behind the snake.

Play this demo in full screen.

5) Create obstacles for your snake to avoid.

Play this demo in full screen.

6) Have the game stop if the snake touches its tail, or if it touches any of the obstacles.

Play this demo in full screen.

7) When the game stops, display to the player that the game is over.

Play this demo in full screen.

8) Make it so that when the game ends, if you press a button ("R" is used in the demo), the game resets (position, score, and tail).

Play this demo in full screen.

9) At the start of the game, display how to play the game to the player. Have the game start by pressing a button ("Space" is used in the demo), and have the displayed information stop when the game starts.

Play this demo in full screen.

Challenge: Make a "difficulty counter." Make it so that if the difficulty increases, the snake moves faster, and if the difficulty decreases, the snake moves slower. Display the difficulty to the player (you may have to adjust the way the snake's tail follows the head to make it work). In the demo, the difficulty is changed when you hit the up or down arrow.

Play this demo in full screen.


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to Joinity — Joinity: the blog</title>
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/assets/app.css">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/images/logo.png"/>
    <link href="/feed.xml" rel="alternate" type="application/rss+xml" title="Joinity: the blog" />
    <meta name="title" content="Welcome to Joinity ">
    <link rel="canonical" href="http://blog.joinity.com/2013/10/09/another-post/">

    <link rel="author" href="https://plus.google.com/2323123123">
    <meta property="og:title" content="Welcome to Joinity "/>
    <meta property="og:url" content="http://blog.joinity.com/2013/10/09/another-post/"/>

    <meta property="og:image" content="http://blog.joinity.com/images/blog-cover.jpg"/>

    <meta property="og:image" content="http://blog.joinity.com/images/logo.png"/>

    <meta property="og:description" content="Cras mattis consectetur purus sit amet fermentum. Cras mattis consectetur purus sit amet fermentum."/>
    <meta name="description" content="Cras mattis consectetur purus sit amet fermentum. Cras mattis consectetur purus sit amet fermentum."/>

    <meta property="og:site_name" content="Joinity: the blog">

            Blog
            Product
            About

            Do you want to join our beta?
            Learn More

                By <address>Fernando Guirao —
                <time pubdate datetime="2013-09-October" title="October 09, 2013">October 09, 2013</time>

Welcome to Joinity

What's in the box

Hello

            <address>

Written by Fernando Guirao

                Co-founder, Product design

            </address>

        © 2013

            Joinity ·
            Blog ·
            Product ·
            About


text:
"use strict";

/* Error Logger
 * ============
 * Logs any error for administrative review.
 *
 * ========================================================================= */

var middleware = function(err, req, res, next) {
    var log     = req.app.locals.log;
    var details = {"req": req, "res": res, "err": err};

    switch (err) {
    case 400:
        log.warn(details, "A bad request came in.");
        break;

    case 401:
        log.warn(details, "Someone failed authorization.");
        break;

    case 404:
        log.info({url: req.originalUrl}, "Someone tried getting a non-existent resource.");
        break;

    case 501:
        log.warn(details, "Someone tried using a request method we do not implement.");
        break;

    default:
        log.error(details, "An internal server error occured.");
        break;
    }

    next(err);
};

module.exports = middleware;


text:
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/runtime.h"

#include "py/nlr.h"
#include "py/runtime.h"

#include "gfx.h"
#include "ugfx_containers.h"
#include "ugfx_styles.h"
#include "ugfx_widgets.h"

extern const mp_obj_type_t ugfx_type;


text:
<?php

namespace spec\PhpSpec\Formatter\Presenter\Value;

use PhpSpec\Formatter\Presenter\Value\StringTypePresenter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class TruncatingStringTypePresenterSpec extends ObjectBehavior
{
    function let(StringTypePresenter $stringTypePresenter)
    {
        $this->beConstructedWith($stringTypePresenter);
    }

    function it_is_a_string_type_presenter()
    {
        $this->shouldImplement('PhpSpec\Formatter\Presenter\Value\StringTypePresenter');
    }

    function it_should_support_string_values(StringTypePresenter $stringTypePresenter)
    {
        $stringTypePresenter->supports('foo')->willReturn(true);
        $this->supports('foo')->shouldReturn(true);
    }

    function it_should_pass_short_values_directly_to_the_decorated_string_type_presenter(
        StringTypePresenter $stringTypePresenter
    ) {
        $stringTypePresenter->present('foo')->willReturn('zfooz');
        $this->present('foo')->shouldReturn('zfooz');
    }

    function it_should_return_long_values_truncated(
        StringTypePresenter $stringTypePresenter
    ) {
        $stringTypePresenter->present('some_string_longer_than_t...')
            ->willReturn('some_string_longer_than_t...');
        $this->present('some_string_longer_than_twenty_five_chars')->shouldReturn('some_string_longer_than_t...');
    }

    function it_presents_only_first_line_of_multiline_string(StringTypePresenter $stringTypePresenter)
    {
        $stringTypePresenter->present('some...')->willReturn('some...');
        $this->present("some\nmultiline\nvalue")->shouldReturn('some...');
    }
}


text:
source env/bin/activate
sudo env/bin/python manage.py collectstatic
pushd staticfiles/
sudo chown -R nginx:nginx .
popd


text:
public class JavaClass {
    public Integer <caret>field= staticMethod();

    public static Integer staticMethod() {
        return 42;
    }
}


text:
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions

from openstack_dashboard.api import glance

def get_available_images(request, project_id=None, images_cache=None):
    """
    Returns a list of images that are public or owned by the given
    project_id. If project_id is not specified, only public images
    are returned.

    :param images_cache:
    An optional dict-like object in which to
    cache public and per-project id image metadata.
    """
    if images_cache is None:
        images_cache = {}
    public_images = images_cache.get('public_images', [])
    images_by_project = images_cache.get('images_by_project', {})
    if 'public_images' not in images_cache:
        public = {"is_public": True,
                  "status": "active"}
        try:
            images, _more = glance.image_list_detailed(
                request, filters=public)
            [public_images.append(image) for image in images]
            images_cache['public_images'] = public_images
        except:
            exceptions.handle(request,
                              _("Unable to retrieve public images."))

    # Preempt if we don't have a project_id yet.
    if project_id is None:
        images_by_project[project_id] = []

    if project_id not in images_by_project:
        owner = {"property-owner_id": project_id,
                 "status": "active"}
        try:
            owned_images, _more = glance.image_list_detailed(
                request, filters=owner)
        except:
            exceptions.handle(request,
                              _("Unable to retrieve images for "
                                "the current project."))
        images_by_project[project_id] = owned_images
    if 'images_by_project' not in images_cache:
        images_cache['images_by_project'] = images_by_project

    owned_images = images_by_project[project_id]
    images = owned_images + public_images

    # Remove duplicate images
    image_ids = []
    final_images = []
    for image in images:
        if image.id not in image_ids:
            image_ids.append(image.id)
            final_images.append(image)
    return [image for image in final_images
            if image.container_format not in ('aki', 'ari')]


text:
//Problem 9. Exchange Variable Values

//Declare two integer variables a and b and assign them with 5 and 10 and after that exchange their values by using some programming logic.
//Print the variable values before and after the exchange.

using System;
class ExchangeValue
{
    static void Main()
    {
        int a = new int();
        int b = new int();
        int c = new int();
        a = 5;
        b = 10;
        Console.WriteLine("a = {0}, b = {1}", a, b);
        c = a;
        a = b;
        b = c;
        Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}