text:
package com.whitelaning.whitefragment.thirdparty.okhttp.log;

import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Created by zhy on 16/3/1.
 */
public class LoggerInterceptor implements Interceptor {
    public static final String TAG = "OkHttpUtils";
    private String tag;
    private boolean showResponse;

    public LoggerInterceptor(String tag, boolean showResponse) {
        if (TextUtils.isEmpty(tag)) {
            tag = TAG;
        }
        this.showResponse = showResponse;
        this.tag = tag;
    }

    public LoggerInterceptor(String tag) {
        this(tag, false);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        logForRequest(request);
        Response response = chain.proceed(request);
        return logForResponse(response);
    }

    private Response logForResponse(Response response) {
        try {
            //===>response log
            Log.e(tag, "========response'log=======");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            Log.e(tag, "url : " + clone.request().url());
            Log.e(tag, "code : " + clone.code());
            Log.e(tag, "protocol : " + clone.protocol());
            if (!TextUtils.isEmpty(clone.message()))
                Log.e(tag, "message : " + clone.message());

            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        Log.e(tag, "responseBody's contentType : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            Log.e(tag, "responseBody's content : " + resp);

                            body = ResponseBody.create(mediaType, resp);
                            return response.newBuilder().body(body).build();
                        } else {
                            Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                        }
                    }
                }
            }

            Log.e(tag, "========response'log=======end");
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return response;
    }

    private void logForRequest(Request request) {
        try {
            String url = request.url().toString();
            Headers headers = request.headers();

            Log.e(tag, "========request'log=======");
            Log.e(tag, "method : " + request.method());
            Log.e(tag, "url : " + url);
            if (headers != null && headers.size() > 0) {
                Log.e(tag, "headers : " + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    Log.e(tag, "requestBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        Log.e(tag, "requestBody's content : " + bodyToString(request));
                    } else {
                        Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
            Log.e(tag, "========request'log=======end");
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")
                    )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }
}


text:
package org.wso2.carbon.sample.mqttclient;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MQTTClient {

    private static Logger log = Logger.getLogger(MQTTClient.class);
    private static List<String> messagesList = new ArrayList<>();
    private static BufferedReader bufferedReader = null;
    private static StringBuffer message = new StringBuffer("");
    private static final String messageEndLine = "*****";

    public static void main(String args[]) {
        String url = args[0];
        String topic = args[1];
        String filePath = args[2];
        String sampleNumber = null;
        if (args.length == 4) {
            sampleNumber = args[3];
        }

        log.info("Starting MQTT Client");
        MqttConnectOptions connOpt = new MqttConnectOptions();
        connOpt.setCleanSession(true);
        connOpt.setKeepAliveInterval(30);

        try {
            MqttClient mqttClient = new MqttClient(url, "SIMPLE-MQTT-PUB");
            mqttClient.connect(connOpt);

            try {
                filePath = MQTTClientUtil.getMessageFilePath(sampleNumber, filePath, topic);
                readMsg(filePath);

                for (String message : messagesList) {
                    log.info("Sending message:");
                    log.info(message);
                    int pubQoS = 1;
                    MqttMessage mqttMessage = new MqttMessage(message.getBytes());
                    mqttMessage.setQos(pubQoS);
                    mqttClient.publish(topic, mqttMessage);
                }
                Thread.sleep(500); // Waiting time for the message to be sent

            } catch (Throwable t) {
                log.error("Error when sending the messages", t);
            } finally {
                try {
                    mqttClient.disconnect();
                } catch (MqttException e) {
                    log.error("Error while disconnecting the MQTT client", e);
                }
            }

        } catch (MqttException e) {
            log.error("Error while connecting to MQTT server", e);
        }
    }

    /**
     * Xml messages will be read from the given filepath and stored in the array list (messagesList)
     *
     * @param filePath Text file to be read
     */
    private static void readMsg(String filePath) {

        try {

            String line;
            bufferedReader = new BufferedReader(new FileReader(filePath));
            while ((line = bufferedReader.readLine()) != null) {
                if ((line.equals(messageEndLine.trim()) && !"".equals(message.toString().trim()))) {
                    messagesList.add(message.toString());
                    message = new StringBuffer("");
                } else {
                    message = message.append(String.format("\n%s", line));
                }
            }
            if (!"".equals(message.toString().trim())) {
                messagesList.add(message.toString());
            }

        } catch (IOException e) {
            log.error("Error in reading file " + filePath, e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                log.error("Error occurred when closing the file : " + e.getMessage(), e);
            }
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "admin/change_form.html" %}
{% load i18n %}

{% block object-tools-items %}
{% if not original.locked %}

		{% trans 'Order from supplier' %}

{% endif %}
{{ block.super }}
{% endblock %}


text:
<?php

namespace Funstaff\Tika\Tests;

use Funstaff\Tika\Configuration;

/**
 * ConfigurationTest
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    protected $config;

    public function setUp()
    {
        $this->config = new Configuration(__DIR__.'/../../tika.jar');
    }

    public function testFailedTikaBinaryPath()
    {
        try {
            $config = new Configuration('/tika.jar');
        } catch (\InvalidArgumentException $e) {
            return;
        }
        $this->fail('Tika binary does not exists on this path.');
    }

    public function testFailedJavaBinaryPath()
    {
        try {
            new Configuration(__DIR__.'/../../tika.jar', '/java');
        } catch (\InvalidArgumentException $e) {
            return;
        }
        $this->fail('Java binary does not exists on this path.');
    }

    public function testTikaBinaryPath()
    {
        $this->assertEquals(__DIR__.'/../../tika.jar', $this->config->getTikaBinaryPath());
    }

    public function testJavaBinaryPath()
    {
        $this->assertNull($this->config->getJavaBinaryPath());
    }

    public function testMetadataClass()
    {
        $this->assertEquals('Funstaff\Tika\Metadata', $this->config->getMetadataClass());
        $this->config->setMetadataClass('Funstaff\Tika\MetaFoo');
        $this->assertEquals('Funstaff\Tika\MetaFoo', $this->config->getMetadataClass());
    }

    public function testOutputFormat()
    {
        $this->assertEquals('xml', $this->config->getOutputFormat());
        $this->config->setOutputFormat('text');
        $this->assertEquals('text', $this->config->getOutputFormat());
    }

    public function testFailedOutputFormat()
    {
        try {
            $this->config->setOutputFormat('foo');
        } catch (\InvalidArgumentException $e) {
            return;
        }
        $this->fail('Invalid Output format');
    }

    public function testMetadataOnly()
    {
        $this->assertFalse($this->config->getMetadataOnly());
        $this->config->setMetadataOnly(true);
        $this->assertTrue($this->config->getMetadataOnly());
    }

    public function testOutputEncoding()
    {
        $this->assertEquals('UTF-8', $this->config->getOutputEncoding());
        $this->config->setOutputEncoding('ISO-8859');
        $this->assertEquals('ISO-8859', $this->config->getOutputEncoding());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Sce.Atf.Adaptation;
using Sce.Atf.Dom;

using Sce.Sled.Lua.Dom;
using Sce.Sled.Lua.Resources;
using Sce.Sled.Shared.Services;

namespace Sce.Sled.Lua
{
    public partial class SledLuaCompilerConfigurationsForm : Form
    {
        public SledLuaCompilerConfigurationsForm()
        {
            InitializeComponent();

            // Create edit TextBox
            m_txtBox =
                new TextBox {Visible = false};
            m_txtBox.KeyPress += TxtBoxKeyPress;
            m_txtBox.Leave += TxtBoxLeave;
            m_lstConfigurations.Controls.Add(m_txtBox);

            // Create edit ListBox for big/little options
            m_lstBigLittleBox = new ListBox();
            m_lstBigLittleBox.Items.Add(Big);
            m_lstBigLittleBox.Items.Add(Little);
            m_lstBigLittleBox.Visible = false;
            m_lstBigLittleBox.SelectedIndexChanged += LstBigLittleBoxSelectedIndexChanged;
            m_lstBigLittleBox.Leave += LstBigLittleBoxLeave;
            m_lstConfigurations.Controls.Add(m_lstBigLittleBox);

            // Create edit ListBox for yes/no options
            m_lstYesNoBox = new ListBox();
            m_lstYesNoBox.Items.Add(Yes);
            m_lstYesNoBox.Items.Add(No);
            m_lstYesNoBox.Visible = false;
            m_lstYesNoBox.SelectedIndexChanged += LstYesNoBoxSelectedIndexChanged;
            m_lstYesNoBox.Leave += LstYesNoBoxLeave;
            m_lstConfigurations.Controls.Add(m_lstYesNoBox);

            // Create folder browser dialog
            m_folderBrowserDlg =
                new FolderBrowserDialog
                    {
                        RootFolder = Environment.SpecialFolder.Desktop,
                        ShowNewFolderButton = true,
                        Description = "Select folder"
                    };
        }

        public void AddConfigurations(IList<SledLuaCompileConfigurationType> configurations)
        {
            m_configurations = configurations;

            foreach (var configType in m_configurations)
                m_lstConfigurations.Items.Add(CreateItem(configType));
        }

        private static ListViewItem CreateItem(SledLuaCompileConfigurationType configType)
        {
            var lstItem =
                new ListViewItem(
                    new[]
                        {
                            configType.Name,
                            configType.LittleEndian ? Little : Big,
                            configType.SizeOfInt.ToString(),
                            configType.SizeOfSizeT.ToString(),
                            configType.SizeOfLuaNumber.ToString(),
                            configType.StripDebugInfo ? Yes : No,
                            configType.OutputPath,
                            configType.OutputExtension = Bin,
                            configType.PreserveRelativePathInfo ? Yes : No
                        }) {Tag = configType, Checked = configType.Selected};

            return lstItem;
        }

        private bool VerifyAndCheckIfWeCanCloseForm()
        {
            var bChecked = m_lstConfigurations.CheckedItems.Count > 0;
            if (bChecked)
                return true;

            if (m_configurations.Count <= 0)
                return true;

            // Nothing is checked & configurations exist that can be checked
            DialogResult = DialogResult.None;
            MessageBox.Show(this, "You have to select/check a configuration before closing!",
                            Localization.SledLuaCompiler, MessageBoxButtons.OK, MessageBoxIcon.Stop);

            return false;
        }

        #region Events

        private void SledLuaCompilerConfigurationsFormLoad(object sender, EventArgs e)
        {
            m_bLoaded = true;
        }

        private void BtnAddClick(object sender, EventArgs e)
        {
            var node =
                new DomNode(SledLuaSchema.SledLuaCompileConfigurationType.Type);

            // Create new configuration with default values
            var configType =
                node.As<SledLuaCompileConfigurationType>();

            configType.Name = NewConfiguration;
            configType.LittleEndian = true;
            configType.SizeOfInt = 4;
            configType.SizeOfSizeT = 4;
            configType.SizeOfLuaNumber = 8;
            configType.StripDebugInfo = false;
            configType.OutputPath = m_projectService.Get.AssetDirectory;
            configType.OutputExtension = Bin;
            configType.PreserveRelativePathInfo = true;

            configType.Selected = false;

            // If first configuration then check it or
            // if no other items are checked then check it
            if (m_lstConfigurations.Items.Count <= 0)
                configType.Selected = true;
            else if (m_lstConfigurations.CheckedItems.Count <= 0)
                configType.Selected = true;

            // Add to list of configurations
            m_configurations.Add(configType);

            // Add to ListView
            m_bCheckChanging = true;
            m_lstConfigurations.Items.Add(CreateItem(configType));
            m_bCheckChanging = false;
        }

        private void BtnDeleteClick(object sender, EventArgs e)
        {
            if (m_lstConfigurations.SelectedItems.Count <= 0)
                return;

            var lstItem = m_lstConfigurations.SelectedItems[0];
            if (lstItem == null)
                return;

            var iPos = lstItem.Index;

            var configType =
                lstItem.Tag as SledLuaCompileConfigurationType;

            if (configType == null)
                return;

            // Remove from list of configurations
            m_configurations.Remove(configType);

            // Remove from ListView
            m_lstConfigurations.Items.Remove(lstItem);

            if (m_lstConfigurations.Items.Count <= 0)
                return;

            // Try and select an item if there are still items on the list
            if (iPos >= m_lstConfigurations.Items.Count)
                iPos = m_lstConfigurations.Items.Count - 1;

            m_lstConfigurations.Items[iPos].Selected = true;

            // Check last remaining item
            if (m_lstConfigurations.Items.Count == 1)
            {
                m_bCheckChanging = true;
                m_lstConfigurations.Items[0].Checked = true;
                m_bCheckChanging = false;
            }
        }

        private void BtnCloseClick(object sender, EventArgs e)
        {
            Close();
        }

        private void LstConfigurationsSelectedIndexChanged(object sender, EventArgs e)
        {
            var bItemSelected = (m_lstConfigurations.SelectedItems.Count != 0);

            m_btnDelete.Enabled = bItemSelected;
        }

        private void LstConfigurationsBeforeLabelEdit(object sender, LabelEditEventArgs e)
        {
            var lstView = sender as ListView;
            if (lstView == null)
                return;

            e.CancelEdit = true;

            // Get mouse position in client coordinates
            var clientPoint = lstView.PointToClient(MousePosition);

            // Find out which item was actually clicked
            var lstItem = lstView.GetItemAt(clientPoint.X, clientPoint.Y);
            if (lstItem == null)
                return;

            // Find out which sub-item was actually clicked
            var lstSubItem =
                lstItem.GetSubItemAt(clientPoint.X, clientPoint.Y);

            // Find column number
            var iColumn = 0;
            if (lstItem.Bounds != lstSubItem.Bounds)
                iColumn = lstItem.SubItems.IndexOf(lstSubItem);

            // Set editing control
            Control ctrl = null;
            switch (iColumn)
            {
                case 1: ctrl = m_lstBigLittleBox; break;
                case 5:
                case 8: ctrl = m_lstYesNoBox; break;
                case 6:
                {
                    var configType =
                        lstItem.Tag as SledLuaCompileConfigurationType;

                    if (configType == null)
                        return;

                    m_folderBrowserDlg.SelectedPath = configType.OutputPath;
                    if (m_folderBrowserDlg.ShowDialog(this) == DialogResult.OK)
                    {
                        var path = m_folderBrowserDlg.SelectedPath;
                        configType.OutputPath = path;
                        lstSubItem.Text = path;
                    }
                }
                break;
                default: ctrl = m_txtBox; break;
            }

            if (ctrl == null)
                return;

            // Set up editing control
            ctrl.Tag = lstSubItem;
            ctrl.Location = lstSubItem.Bounds.Location;
            ctrl.Width = lstSubItem.Bounds.Width;
            if (ctrl is TextBox)
                ctrl.Height = lstSubItem.Bounds.Height;
            ctrl.Text = lstSubItem.Text;
            ctrl.Visible = true;
            ctrl.BringToFront();
            ctrl.Focus();
        }

        private void LstConfigurationsItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (!m_bLoaded)
                return;

            if (m_bCheckChanging)
                return;

            try
            {
                m_bCheckChanging = true;

                // Uncheck all
                foreach (ListViewItem lstItem in m_lstConfigurations.CheckedItems)
                    lstItem.Checked = false;

                // Un-select all
                foreach (var ct in m_configurations)
                    ct.Selected = false;

                // Check item being changed
                e.Item.Checked = true;

                var configType =
                    e.Item.Tag as SledLuaCompileConfigurationType;

                if (configType == null)
                    return;

                // Select item being checked
                configType.Selected = true;
            }
            finally
            {
                m_bCheckChanging = false;
            }
        }

        private void TxtBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            var lstSubItem =
                m_txtBox.Tag as ListViewItem.ListViewSubItem;

            if (lstSubItem == null)
                return;

            if (e.KeyChar == (char)Keys.Return)
            {
                try
                {
                    var value = m_txtBox.Text.Trim();
                    var origValue = lstSubItem.Text.Trim();

                    // Find the ListViewItem the sub-item belongs to
                    var lstItem =
                        m_lstConfigurations.GetItemAt(lstSubItem.Bounds.X, lstSubItem.Bounds.Y);

                    if (lstItem == null)
                        return;

                    // Find column number
                    var iColumn = 0;
                    if (lstItem.Bounds != lstSubItem.Bounds)
                        iColumn = lstItem.SubItems.IndexOf(lstSubItem);

                    // Sync to DOM object
                    var configType =
                        lstItem.Tag as SledLuaCompileConfigurationType;

                    if (configType == null)
                        return;

                    var bSuccessfulValueChange = false;

                    switch (iColumn)
                    {
                        // Name
                        case 0:
                            configType.Name = value;
                            bSuccessfulValueChange = true;
                            break;

                        // Endian
                        case 1:
                            //  Big/Little not handled here
                            break;

                        // sizeof(int)
                        case 2:
                        {
                            int iValue;
                            if (int.TryParse(value, out iValue))
                            {
                                // Make sure iValue is one of the valid values
                                if (m_lstValidSizeofIntValues.Contains(iValue))
                                {
                                    configType.SizeOfInt = iValue;
                                    bSuccessfulValueChange = true;
                                }
                            }

                            // Show tooltip if invalid values
                            if (!bSuccessfulValueChange)
                                ShowListViewSubItemToolTip(
                                    ListToString(m_lstValidSizeofIntValues), lstSubItem);
                        }
                        break;

                        // sizeof(size_t)
                        case 3:
                        {
                            int iValue;
                            if (int.TryParse(value, out iValue))
                            {
                                // Make sure iValue is one of the valid values
                                if (m_lstValidSizeofSizeTValues.Contains(iValue))
                                {
                                    configType.SizeOfSizeT = iValue;
                                    bSuccessfulValueChange = true;
                                }
                            }

                            // Show tooltip if invalid values
                            if (!bSuccessfulValueChange)
                                ShowListViewSubItemToolTip(
                                    ListToString(m_lstValidSizeofSizeTValues), lstSubItem);
                        }
                        break;

                        // sizeof(lua_Number)
                        case 4:
                        {
                            int iValue;
                            if (int.TryParse(value, out iValue))
                            {
                                // Make sure iValue is one of the valid values
                                if (m_lstValidSizeofLuaNumberValues.Contains(iValue))
                                {
                                    configType.SizeOfLuaNumber = iValue;
                                    bSuccessfulValueChange = true;
                                }
                            }

                            // Show tooltip if invalid values
                            if (!bSuccessfulValueChange)
                                ShowListViewSubItemToolTip(
                                    ListToString(m_lstValidSizeofLuaNumberValues), lstSubItem);
                        }
                        break;

                        // Strip Debug Info
                        case 5:
                            // Yes/No not handled here
                            break;

                        // Output Path
                        case 6:
                            // Not handled here
                            break;

                        // Output Extension
                        case 7:
                        {
                            if (value.StartsWith("."))
                                value = value.Remove(0, 1);

                            configType.OutputExtension = value;
                            bSuccessfulValueChange = true;
                        }
                        break;
                    }

                    // Update item text
                    lstSubItem.Text = bSuccessfulValueChange ? value : origValue;
                }
                finally
                {
                    // Hide box
                    m_txtBox.Visible = false;
                    m_txtBox.Tag = null;
                    e.Handled = true;
                }
            }
        }

        private void TxtBoxLeave(object sender, EventArgs e)
        {
            // Hide TextBox
            m_txtBox.Visible = false;
            m_txtBox.Tag = null;
        }

        private void LstBigLittleBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (!m_lstBigLittleBox.Visible)
                return;

            var lstSubItem =
                m_lstBigLittleBox.Tag as ListViewItem.ListViewSubItem;

            if (lstSubItem == null)
                return;

            try
            {
                var value = m_lstBigLittleBox.Text;

                // Find the ListViewItem the sub-item belongs to
                var lstItem =
                    m_lstConfigurations.GetItemAt(lstSubItem.Bounds.X, lstSubItem.Bounds.Y);

                if (lstItem == null)
                    return;

                var configType =
                    lstItem.Tag as SledLuaCompileConfigurationType;

                if (configType == null)
                    return;

                // Sync to DOM object
                configType.LittleEndian = string.Compare(value, Little, StringComparison.Ordinal) == 0;

                // Update ListView
                lstSubItem.Text = value;
            }
            finally
            {
                m_lstBigLittleBox.Visible = false;
                m_lstBigLittleBox.Tag = null;
            }
        }

        private void LstBigLittleBoxLeave(object sender, EventArgs e)
        {
            // Hide ListBox
            m_lstBigLittleBox.Visible = false;
            m_lstBigLittleBox.Tag = null;
        }

        private void LstYesNoBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (!m_lstYesNoBox.Visible)
                return;

            var lstSubItem =
                m_lstYesNoBox.Tag as ListViewItem.ListViewSubItem;

            if (lstSubItem == null)
                return;

            try
            {
                var value = m_lstYesNoBox.Text;

                // Find the ListViewItem the sub-item belongs to
                var lstItem =
                    m_lstConfigurations.GetItemAt(lstSubItem.Bounds.X, lstSubItem.Bounds.Y);

                if (lstItem == null)
                    return;

                // Find column number
                var iColumn = 0;
                if (lstItem.Bounds != lstSubItem.Bounds)
                    iColumn = lstItem.SubItems.IndexOf(lstSubItem);

                var configType =
                    lstItem.Tag as SledLuaCompileConfigurationType;

                if (configType == null)
                    return;

                // Sync to DOM object
                switch (iColumn)
                {
                    case 5:
                        configType.StripDebugInfo = string.Compare(value, Yes, StringComparison.Ordinal) == 0;
                        break;

                    case 8:
                        configType.PreserveRelativePathInfo = string.Compare(value, Yes, StringComparison.Ordinal) == 0;
                        break;
                }

                // Update ListView
                lstSubItem.Text = value;
            }
            finally
            {
                m_lstYesNoBox.Visible = false;
                m_lstYesNoBox.Tag = null;
            }
        }

        private void LstYesNoBoxLeave(object sender, EventArgs e)
        {
            // Hide ListBox
            m_lstYesNoBox.Visible = false;
            m_lstYesNoBox.Tag = null;
        }

        private void SledLuaCompilerConfigurationsFormFormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !VerifyAndCheckIfWeCanCloseForm();
        }

        #endregion

        private static string ListToString(IEnumerable<int> lstValues)
        {
            var sb = new StringBuilder();

            var bFirst = true;
            foreach (var value in lstValues)
            {
                if (!bFirst)
                    sb.Append(", ");

                sb.Append(value);

                if (bFirst)
                    bFirst = false;
            }

            return sb.ToString();
        }

        private void ShowListViewSubItemToolTip(string validValues, ListViewItem.ListViewSubItem lstSubItem)
        {
            var point =
                new Point(lstSubItem.Bounds.Right - 16, lstSubItem.Bounds.Top - 40);

            var toolTip =
                new ToolTip {IsBalloon = true};
            toolTip.Show("Valid values: " + validValues, m_lstConfigurations, point, 5000);
        }

        private IList<SledLuaCompileConfigurationType> m_configurations;

        private bool m_bLoaded;
        private bool m_bCheckChanging;

        private TextBox m_txtBox;
        private ListBox m_lstBigLittleBox;
        private ListBox m_lstYesNoBox;
        private FolderBrowserDialog m_folderBrowserDlg;

        private readonly List<int> m_lstValidSizeofIntValues =
            new List<int>(new[] { 2, 4, 8 }); // short/int/__int64

        private readonly List<int> m_lstValidSizeofSizeTValues =
            new List<int>(new[] { 2, 4, 8 }); // short/int/__int64

        private readonly List<int> m_lstValidSizeofLuaNumberValues =
            new List<int>(new[] { 4, 8 }); // float/double

        private const string NewConfiguration = "New configuration";
        private const string Bin = "bin";
        private const string Little = "Little";
        private const string Big = "Big";
        private const string Yes = "Yes";
        private const string No = "No";

        private readonly SledServiceReference<ISledProjectService> m_projectService =
            new SledServiceReference<ISledProjectService>();
    }
}


text:
using System.Collections.Generic;
using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;

namespace Atata.Tests
{
    [TestFixture]
    public class ObjectCreatorTests
    {
        private ObjectCreator _sut;

        [SetUp]
        public void SetUp()
        {
            IObjectConverter objectConverter = new ObjectConverter();
            IObjectMapper objectMapper = new ObjectMapper(objectConverter);

            _sut = new ObjectCreator(objectConverter, objectMapper);
        }

        [Test]
        public void ObjectCreator_Create_Empty()
        {
            object result = _sut.Create(
                typeof(IgnoreInitAttribute),
                new Dictionary<string, object>());

            result.Should().BeOfType<IgnoreInitAttribute>();
        }

        [Test]
        public void ObjectCreator_Create_WithPropertyValues_ForTypeWithDefaultConstructor()
        {
            object result = _sut.Create(
                typeof(TraceLogAttribute),
                new Dictionary<string, object>
                {
                    ["targetName"] = "SomeName",
                    ["targetParentTypes"] = new[] { nameof(InputPage), nameof(TablePage) }
                });

            var castedResult = result.Should().BeOfType<TraceLogAttribute>().Subject;

            using (new AssertionScope())
            {
                castedResult.TargetNames.Should().Equal("SomeName");
                castedResult.TargetParentTypes.Should().Equal(typeof(InputPage), typeof(TablePage));
            }
        }

        [Test]
        public void ObjectCreator_Create_WithPropertyValues_ForTypeWithoutDefaultConstructor()
        {
            object result = _sut.Create(
                typeof(FindByIdAttribute),
                new Dictionary<string, object>
                {
                    ["targetName"] = "SomeName",
                    ["targetParentTypes"] = new[] { nameof(InputPage), nameof(TablePage) }
                });

            var castedResult = result.Should().BeOfType<FindByIdAttribute>().Subject;

            using (new AssertionScope())
            {
                castedResult.TargetNames.Should().Equal("SomeName");
                castedResult.TargetParentTypes.Should().Equal(typeof(InputPage), typeof(TablePage));
            }
        }

        [Test]
        public void ObjectCreator_Create_WithConstructorParametersAndPropertyValues()
        {
            object result = _sut.Create(
                typeof(FindByIdAttribute),
                new Dictionary<string, object>
                {
                    ["match"] = TermMatch.StartsWith,
                    ["values"] = new[] { "val1", "val2" },
                    ["format"] = "{0}!"
                });

            var castedResult = result.Should().BeOfType<FindByIdAttribute>().Subject;

            using (new AssertionScope())
            {
                castedResult.Match.Should().Be(TermMatch.StartsWith);
                castedResult.Values.Should().Equal(new[] { "val1", "val2" });
                castedResult.Format.Should().Be("{0}!");
            }
        }

        [Test]
        public void ObjectCreator_Create_WithAlternativeConstructorParameterName_Value()
        {
            object result = _sut.Create(
                typeof(FindByIdAttribute),
                new Dictionary<string, object>
                {
                    ["match"] = TermMatch.EndsWith,
                    ["value"] = "val1"
                },
                new Dictionary<string, string>
                {
                    ["value"] = "values",
                    ["case"] = "termCase"
                });

            var castedResult = result.Should().BeOfType<FindByIdAttribute>().Subject;

            using (new AssertionScope())
            {
                castedResult.Match.Should().Be(TermMatch.EndsWith);
                castedResult.Values.Should().Equal(new[] { "val1" });
            }
        }

        [Test]
        public void ObjectCreator_Create_WithAlternativeConstructorParameterName_Case()
        {
            object result = _sut.Create(
                typeof(FindByIdAttribute),
                new Dictionary<string, object>
                {
                    ["case"] = TermCase.LowerMerged,
                    ["match"] = TermMatch.EndsWith
                },
                new Dictionary<string, string>
                {
                    ["value"] = "values",
                    ["case"] = "termCase"
                });

            var castedResult = result.Should().BeOfType<FindByIdAttribute>().Subject;

            using (new AssertionScope())
            {
                castedResult.Match.Should().Be(TermMatch.EndsWith);
                castedResult.Case.Should().Be(TermCase.LowerMerged);
            }
        }
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Roslyn.Utilities
{
    internal interface IAsyncEnumerator<out T> : IDisposable
    {
        T Current { get; }
        Task<bool> MoveNextAsync(CancellationToken cancellationToken);
    }
}


text:
package PM;

public class Tipo_de_escala implements Comparable<Tipo_de_escala> {

    private int dias_trabalhados;
    private int dias_descansados;

    public int getDias_trabalhados() {
        return dias_trabalhados;
    }

    public void setDias_trabalhados(int dias_trabalhados) {
        this.dias_trabalhados = dias_trabalhados;
    }

    public int getDias_descansados() {
        return dias_descansados;
    }

    public void setDias_descansados(int dias_descansados) {
        this.dias_descansados = dias_descansados;
    }

    public int getDias_do_ciclo() {
        return dias_descansados + dias_trabalhados;
    }

    @Override
    public String toString() {
        return "Tipo_de_escala{" + "dias_trabalhados=" + dias_trabalhados + ", dias_descansados=" + dias_descansados + '}';
    }

    @Override
    public int compareTo(Tipo_de_escala t) {
        return toString().compareTo(t.toString());
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Tipo_de_escala other = (Tipo_de_escala) obj;
        if (this.dias_trabalhados != other.dias_trabalhados)
            return false;
        if (this.dias_descansados != other.dias_descansados)
            return false;
        return true;
    }

}


text:
package org.mockito.internal.stubbing;

import java.util.LinkedList;
import java.util.List;

import org.mockito.exceptions.Reporter;
import org.mockito.internal.stubbing.answers.DoesNothing;
import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.stubbing.answers.ThrowsException;
import org.mockito.internal.util.MockUtil;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Stubber;

@SuppressWarnings("unchecked")
public class StubberImpl implements Stubber {

    final List<Answer> answers = new LinkedList<Answer>();
    private final Reporter reporter = new Reporter();

    public <T> T when(T mock) {
        MockUtil mockUtil = new MockUtil();

        if (mock == null) {
            reporter.nullPassedToWhenMethod();
        } else {
            if (!mockUtil.isMock(mock)) {
                reporter.notAMockPassedToWhenMethod();
            }
        }

        mockUtil.getMockHandler(mock).setAnswersForStubbing(answers);
        return mock;
    }

    public Stubber doReturn(Object toBeReturned) {
        answers.add(new Returns(toBeReturned));
        return this;
    }

    public Stubber doThrow(Throwable toBeThrown) {
        answers.add(new ThrowsException(toBeThrown));
        return this;
    }

    public Stubber doNothing() {
        answers.add(new DoesNothing());
        return this;
    }

    public Stubber doAnswer(Answer answer) {
        answers.add(answer);
        return this;
    }
}


text:
package com.mixer.api.resource.constellation.events;

import com.mixer.api.resource.constellation.AbstractConstellationEvent;
import com.mixer.api.resource.constellation.events.data.LiveData;

public class LiveEvent extends AbstractConstellationEvent<LiveData> {
    public LiveEvent() {
        this.type = Type.EVENT;
    }
}


text:
import java.io.File;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ImageUploadNfsw {
	// Upload an image first & detect whether it is Not Suitable for Work (NSFW)
	// https://pixlab.io/#/cmd?id=nsfw

	// Your PixLab key
	private static String key = "Pix_Key";

	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

	public static void main(String[] args) throws IOException, JSONException {
		OkHttpClient client = new OkHttpClient();
		HttpUrl httpUrl = new HttpUrl.Builder()
                .scheme("https")
                .host("api.pixlab.io")
                .addPathSegment("nsfw")
                .build();

		File file = new File("local_image.png");
		RequestBody body = new MultipartBody.Builder()
		        .setType(MultipartBody.FORM)
		        .addFormDataPart("file", file.getName(),
		            RequestBody.create(MediaType.parse("png"), file))
		        .addFormDataPart("key", key)
		        .build();

		Request requesthttp = new Request.Builder()
                .addHeader("accept", "application/json")
                .url(httpUrl)
                .post(body)
                .build();

        Response response = client.newCall(requesthttp).execute();

		JSONObject jResponse = new JSONObject(response.body().string());
		if (jResponse.getInt("status") != 200) {
			System.out.println("Error :: " + jResponse.getString("error"));
			System.exit(1);
		}else {
			System.out.println("NSFW Score: "+ jResponse.getString("score"));
		}
	}

}


text:
package sistemapagoimpuestos.View.Admin.GestionarTipoImpuesto;

import exceptions.Excepciones;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import sistemapagoimpuestos.Controller.ControladorGestionarTipoImpuesto;
import sistemapagoimpuestos.Dto.DTOEmpresaTipImpItem;
import sistemapagoimpuestos.Dto.DTOEmpresaTipoImpuestoItems;
import sistemapagoimpuestos.Dto.DTOItem;
import sistemapagoimpuestos.Dto.DTOTipoImpuesto;
import sistemapagoimpuestos.Dto.DtoItemOrden;

/**
 *
 * @author lunamarcos
 */
public class IUGestionarTipoImpuestoModificar extends javax.swing.JFrame {

    ControladorGestionarTipoImpuesto controlador = new ControladorGestionarTipoImpuesto();
    private static List<DTOEmpresaTipImpItem> dTOEmpresaTipImpItemList = new ArrayList<>();

    public static List<DTOEmpresaTipImpItem> getdTOEmpresaTipImpItemList() {
        return dTOEmpresaTipImpItemList;
    }

    public static void setdTOEmpresaTipImpItemList(List<DTOEmpresaTipImpItem> dTOEmpresaTipImpItemList) {
        IUGestionarTipoImpuestoModificar.dTOEmpresaTipImpItemList = dTOEmpresaTipImpItemList;
    }

    public String getNombre_actual() {
        return nombre_actual.getText();
    }

    public void setNombre_actual(String nombre_actual) {
        this.nombre_actual.setText(nombre_actual);
    }

    public static  void adddTOEmpresaTipImpItemList(DTOEmpresaTipImpItem dTOEmpresaTipImpItem){
         if(dTOEmpresaTipImpItemList==null){
            dTOEmpresaTipImpItemList = new ArrayList<>();
        }
        dTOEmpresaTipImpItemList.add(dTOEmpresaTipImpItem);
    }
    public static void removedTOEmpresaTipImpItemList(int index){
       dTOEmpresaTipImpItemList.remove(index);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
        public IUGestionarTipoImpuestoModificar( String cuitEmpresa) {

    }

    public IUGestionarTipoImpuestoModificar() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        label_nombre = new javax.swing.JLabel();
        label_deshabilitar = new javax.swing.JLabel();
        label_esEditable = new javax.swing.JLabel();
        textfield_nombre = new javax.swing.JTextField();
        checkbox_habilitado = new javax.swing.JCheckBox();
        checkbox_esEditable = new javax.swing.JCheckBox();
        button_modificar = new javax.swing.JButton();
        nombre_actual = new javax.swing.JLabel();
        cancel_button = new javax.swing.JButton();
        label_fecha = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        label_nombre.setText("Nombre");
        label_nombre.setToolTipText("");

        label_deshabilitar.setText("Habilitado");

        label_esEditable.setText("Es editable");

        textfield_nombre.setToolTipText("");
        textfield_nombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textfield_nombreActionPerformed(evt);
            }
        });

        checkbox_habilitado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkbox_habilitadoActionPerformed(evt);
            }
        });

        checkbox_esEditable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkbox_esEditableActionPerformed(evt);
            }
        });

        button_modificar.setText("Modificar");
        button_modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_modificarActionPerformed(evt);
            }
        });

        nombre_actual.setForeground(new java.awt.Color(240, 240, 240));
        nombre_actual.setText("nombreActual");

        cancel_button.setText("Cancelar");
        cancel_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancel_buttonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addComponent(cancel_button)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(button_modificar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(119, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(label_deshabilitar)
                                .addComponent(label_esEditable))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(label_nombre)))
                        .addGap(94, 94, 94)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(checkbox_esEditable)
                            .addComponent(textfield_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(checkbox_habilitado, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(label_fecha))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(nombre_actual)))))
                .addGap(56, 56, 56))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(128, 128, 128)
                                .addComponent(nombre_actual))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(49, 49, 49)
                                .addComponent(label_fecha)))
                        .addGap(66, 66, 66)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cancel_button)
                            .addComponent(button_modificar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(textfield_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(label_nombre))
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(checkbox_habilitado)
                            .addComponent(label_deshabilitar))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(label_esEditable)
                            .addComponent(checkbox_esEditable))))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void button_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_modificarActionPerformed
        // TODO add your handling code here:
        try{
            if(textfield_nombre.getText().equals("")){
                textfield_nombre.setText(null);
                throw new java.lang.NumberFormatException();
            }
            controlador.modificarTipoImpuesto(textfield_nombre.getText(), nombre_actual.getText(), checkbox_esEditable.isSelected(), checkbox_habilitado.isSelected(), dTOEmpresaTipImpItemList);
            this.dispose();
            controlador.iniciar();
        }catch(java.lang.NumberFormatException e){
            Excepciones.getInstance().camposRequerido(Arrays.asList("Nombre"));
        }
    }//GEN-LAST:event_button_modificarActionPerformed

    private void textfield_nombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textfield_nombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textfield_nombreActionPerformed

    private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed
        this.dispose();
        controlador.iniciar();
    }//GEN-LAST:event_cancel_buttonActionPerformed

    private void checkbox_habilitadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkbox_habilitadoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkbox_habilitadoActionPerformed

    private void checkbox_esEditableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkbox_esEditableActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkbox_esEditableActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IUGestionarTipoImpuestoModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                // Asociacion con el controlador
                IUGestionarTipoImpuestoModificar pantallaModificar = new IUGestionarTipoImpuestoModificar();

            }
        });
    }

    // Getters

    public String getTextfield_nombre() {
        return textfield_nombre.getText();
    }

    public void setTextfield_nombre(String text) {
        this.textfield_nombre.setText(text);
    }

    public boolean getCheckbox_deshabilitar() {
        return checkbox_habilitado.isSelected();
    }

    public void setCheckbox_Habilitar(boolean habilitado) {
        this.checkbox_habilitado.setSelected(habilitado);
    }

    public boolean getCheckbox_esEditable() {
        return checkbox_esEditable.isSelected();
    }

    public void setCheckbox_esEditable(boolean editable) {
        this.checkbox_esEditable.setSelected(editable);
    }

    public JLabel getLabel_fecha() {
        return label_fecha;
    }

    public void setLabel_fecha(JLabel label_fecha) {
        this.label_fecha = label_fecha;
    }

    public String getLabel_nombre() {
        return label_nombre.getText();
    }

    public void setLabel_nombre(String nombre) {
        this.label_nombre.setText(nombre);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton button_modificar;
    private javax.swing.JButton cancel_button;
    private javax.swing.JCheckBox checkbox_esEditable;
    private javax.swing.JCheckBox checkbox_habilitado;
    private javax.swing.JLabel label_deshabilitar;
    private javax.swing.JLabel label_esEditable;
    private javax.swing.JLabel label_fecha;
    private javax.swing.JLabel label_nombre;
    private javax.swing.JLabel nombre_actual;
    private javax.swing.JTextField textfield_nombre;
    // End of variables declaration//GEN-END:variables
}


text:
layout:     post
title:      "ECMAScript 6"
subtitle:   "The Latest In ECMAScript 6"
date:       2015-08-20 12:00:00
author:     "Chris Salvi"
header-img: "img/post-bg-04.jpg"
---

## Background on Chris

Chris is an alumni of the Firehose Project who sees JavaScript as not so bad and has found ECMAScript 6 to be particularly a low barrier to entry for Ruby developers to get working on JavaScript.

You can read about Chris demystifying JavaScript's notorious "this" keyword [here](https://medium.com/@cdiddy42/javascript-s-notorious-this-keyword-demystified-80ba2234c77c).

{% include youtubePlayer.html id="Lr8NUzuKtQI" %}

Watch the full video [here](https://www.youtube.com/watch?v=fk7AQFLhFTE).


text:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <libox.h>
#include <nvme.h>
#include <nvmef.h>

#define PARSER_FABRICS_COUNT   1

extern struct core_struct core;

static int parser_fabrics_connect (NvmeRequest *req, NvmeCmd *cmd)
{
    NvmefConnect *connect = (NvmefConnect *) cmd;

    if (nvmef_create_queue (connect->qid)) {
        req->status = 0x4000 | NVME_INTERNAL_DEV_ERROR;
        return -1;
    }

    return NVME_SUCCESS;
}

static int parser_fabrics_exec (NvmeRequest *req, NvmeCmd *cmd)
{
    NvmefCmd *fcmd = (NvmefCmd *) cmd;

    if (core.debug)
        printf ("[FABRICS: cftype: 0x%02x]\n", fcmd->fctype);

    switch (fcmd->fctype) {
        case NVMEF_CMD_CONNECT:
            return parser_fabrics_connect (req, cmd);
            break;

        /* Commands not supported yet */
        case NVMEF_CMD_PROP_SET:
        case NVMEF_CMD_PROP_GET:
        case NVMEF_CMD_AUTH_SEND:
        case NVMEF_CMD_AUTH_RECV:
        default:
            log_err ("[fabrics: Command %x not supported.]", fcmd->fctype);
            req->status = NVME_INVALID_OPCODE;
            return -1;
    }
}

static struct nvm_parser_cmd fabrics_cmds[PARSER_FABRICS_COUNT] = {
    {
        .name       = "COMMAND_FABRICS",
        .opcode     = 0x7f,
        .opcode_fn  = parser_fabrics_exec,
        .queue_type = NVM_CMD_ADMIN
    }
};

static void parser_fabrics_exit (struct nvm_parser *parser)
{

}

static struct nvm_parser parser_fabrics = {
    .name       = "FABRICS_PARSER",
    .cmd_count  = PARSER_FABRICS_COUNT,
    .exit       = parser_fabrics_exit
};

int parser_fabrics_init (void)
{
    parser_fabrics.cmd = fabrics_cmds;

    return ox_register_parser (&parser_fabrics);
}


text:
Incognito
=========

Plugin for Vanilla forum that allows logged in users to post as one dedicated and as such, anonymous user account.

This plugin is fully customizable regarding user roles, category permission and the user account that is used for the anonymous posts. By default a) no one is allowed to post anonymous and b) posting anonymous is allowed in no category at all. So you **have to** go to www.yourforum.com/dashboard/role and allow incognito posts for one or more roles in one or more categories.

You can also specify which user account to use. You can create a user such as "Ghostwriter", "Anonymous" or "Cyrano" or whatever you like and set the line `$Configuration['Plugins']['Incognito']['UserID'] = '2';` accordingly in `/conf/config.php`


text:
#ifndef CHEMKIT_CONCURRENT_H
#define CHEMKIT_CONCURRENT_H

#include "chemkit.h"

#ifndef Q_MOC_RUN
#include <boost/thread.hpp>
#endif

namespace chemkit {
namespace concurrent {

/// Runs \p function asynchronously in a separate thread. Returns a
/// future containing the value returned from \p function.
///
/// \internal
template<typename Function>
inline boost::shared_future<typename Function::result_type> run(const Function &function)
{
    typedef typename Function::result_type result_type;

    boost::packaged_task<result_type> task(function);
    boost::shared_future<result_type> future(task.get_future());

    // execute task in detached thread
    boost::thread(boost::move(task)).detach();

    return future;
}

} // end concurrent namespace
} // end chemkit namespace

#endif // CHEMKIT_CONCURRENT_H


text:
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef PVD_SCENEVISUALDEBUGGER_H
#define PVD_SCENEVISUALDEBUGGER_H

#if PX_SUPPORT_VISUAL_DEBUGGER

#include "PsUserAllocated.h"
#include "PsArray.h"
#include "CmPhysXCommon.h"
#include "PxMetaDataPvdBinding.h"

namespace physx { namespace debugger {
	namespace comm {
		class PvdDataStream;
	}
	namespace renderer
	{
		class PvdImmediateRenderer;
	}
}}

namespace physx
{

class PxSimulationStatistics;
class PxGeometry;

namespace profile
{
	class PxProfileZone;
}

namespace Scb
{
	class Scene;
	class Actor;
	class Body;
	class RigidStatic;
	class RigidObject;
	class Shape;
	//class Material;
	class ParticleSystem;
	class Constraint;
	class Articulation;
	class ArticulationJoint;
	class Cloth;
}

namespace Sc
{
	class MaterialCore;
	class RigidCore;
	class ConstraintCore;
}

namespace Pvd
{

struct SceneGroups
{
	enum Enum
	{
		RigidDynamics = 1, // 0 is reserved for SimulationStatistics
		RigidStatics,
		Joints,
		Articulations,
		ParticleSystems,
		Materials,
		ProfileZones,
		Cloths,
		NUM_ELEMENTS,
	};
};

//////////////////////////////////////////////////////////////////////////
/*!
RemoteDebug supplies functionality for writing debug info to a stream
to be read by the remote debugger application.
*/
//////////////////////////////////////////////////////////////////////////
class SceneVisualDebugger: public Ps::UserAllocated, public PvdVisualizer
{
public:
	SceneVisualDebugger(Scb::Scene&);
	virtual ~SceneVisualDebugger();

	void setPvdConnection(physx::debugger::comm::PvdDataStream* c, PxU32 inConnectionType);
	physx::debugger::comm::PvdDataStream* getPvdConnection() const;

	// internal methods
	void sendClassDescriptions();
	bool isConnected() const;
	bool isConnectedAndSendingDebugInformation();

	void sendEntireScene();
	void frameStart(PxReal simulateElapsedTime);
	void frameEnd();
	void createPvdInstance();
	void updatePvdProperties();
	void releasePvdInstance();

	void createPvdInstanceIfInvalid(const PxActor* actor); //temporary for articulation link
	void createPvdInstance(const PxActor* actor); // temporary for deformables and particle systems
	void updatePvdProperties(const PxActor* actor);
	void releasePvdInstance(const PxActor* actor); // temporary for deformables and particle systems

	void createPvdInstance(Scb::Actor* scbActor); // temporary for deformables and particle systems
	void updatePvdProperties(Scb::Actor* scbActor);
	void releasePvdInstance(Scb::Actor* scbActor); // temporary for deformables and particle systems

	void createPvdInstance(Scb::Body* scbBody);
	void updatePvdProperties(Scb::Body* scbBody);
	void updateKinematicTarget(Scb::Body* scbBody,const PxTransform& p);

	void createPvdInstance(Scb::RigidStatic* scbRigidStatic);
	void updatePvdProperties(Scb::RigidStatic* scbRigidStatic);

	void releasePvdInstance(Scb::RigidObject* scbRigidObject);

	void createPvdInstance(const Scb::Shape* scbShape);
	void updateMaterials(const Scb::Shape* scbShape);
	void updatePvdProperties(const Scb::Shape* scbShape);
	void releaseAndRecreateGeometry( const Scb::Shape* scbShape );
	void releasePvdInstance(const Scb::Shape* scbShape);

	//void createPvdInstance(const Scb::Material* scbMat);
	//void updatePvdProperties( const Scb::Material* material );
	//void releasePvdInstance(const Scb::Material* scbMat);

	void createPvdInstance(const Sc::MaterialCore* scbMat);
	void updatePvdProperties( const Sc::MaterialCore* material );
	void releasePvdInstance(const Sc::MaterialCore* scbMat);

	void createPvdInstance(Scb::Articulation* articulation);
	void updatePvdProperties(Scb::Articulation* articulation);
	void releasePvdInstance(Scb::Articulation* articulation);

	void updatePvdProperties(Scb::ArticulationJoint* articulationJoint);

	void createPvdInstance(Scb::ParticleSystem* scbParticleSys);
	void updatePvdProperties(Scb::ParticleSystem* scbParticleSys);
	void releasePvdInstance(Scb::ParticleSystem* scbParticleSys);
	void sendArrays(Scb::ParticleSystem* scbParticleSys);

	void createPvdInstance(Scb::Cloth* scbCloth);
	void sendSimpleProperties( Scb::Cloth* cloth );
	void sendMotionConstraints( Scb::Cloth* cloth );
	void sendCollisionSpheres( Scb::Cloth* cloth );
	void sendVirtualParticles( Scb::Cloth* cloth );
	void sendSeparationConstraints( Scb::Cloth* cloth );
	void releasePvdInstance(Scb::Cloth* scbCloth);

	void createPvdInstance(Scb::Constraint* constraint);
	void updatePvdProperties(Scb::Constraint* constraint);
	void releasePvdInstance(Scb::Constraint* constraint);

	void updateContacts();
	void updateSceneQueries();
	void setCreateContactReports(bool);

	void updateJoints();

	//PvdVisualizer
	virtual void visualize( PxArticulationLink& link );

private:
	bool updateConstraint(const Sc::ConstraintCore& scConstraint, PxU32 updateType);

	physx::debugger::comm::PvdDataStream*					mPvdConnection;
	physx::debugger::renderer::PvdImmediateRenderer*		mImmediateRenderer;
	Scb::Scene&							mScbScene;
	Ps::Array<PxU64>					mProfileZoneIdList;
	PxU32								mConnectionType;
	PvdMetaDataBinding					mMetaDataBinding;
};

} // namespace Pvd

}

#endif // PX_SUPPORT_VISUAL_DEBUGGER

#endif // VISUALDEBUGGER_H


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.codepath.apps.mysimpletweets.TimelineActivity">

  <ListView
    android:id="@+id/lvTweets"
    android:layout_width="368dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp"
    android:layout_centerVertical="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />
</RelativeLayout>


text:
// Copyright 2017-present, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)

#pragma once

#include "CoreMinimal.h"
#include "Owl/SLOwlDoc.h"
#include "Individuals/Type/SLBaseIndividual.h"

/**
* Events owl document template types
*/
UENUM(BlueprintType)
enum class ESLOwlExperimentTemplate : uint8
{
	NONE					UMETA(DisplayName = "None"),
	Default					UMETA(DisplayName = "Default"),
	IAI						UMETA(DisplayName = "IAI"),
};

/**
* Semantic events (experiment) document in owl
*/
struct FSLOwlExperiment : FSLOwlDoc
{
protected:
	// Array of timepoint individuals
	TArray<FSLOwlNode> TimepointIndividuals;

	// Set of registered timepoints (in order to avoid multiple individual declaration)
	TArray<float> RegisteredTimepoints;

	// Array of object individuals
	TArray<FSLOwlNode> ObjectIndividuals;

	// Set of registered objects (in order to avoid multiple individual declaration)
	TSet<USLBaseIndividual*> RegisteredObjects;

	// Experiment individual
	FSLOwlNode ExperimentIndividual;

public:
	// Default constructor
	FSLOwlExperiment() {}

	// Init constructor
	FSLOwlExperiment(const FString& InDocPrefix,
		const FString& InDocOntologyName,
		const FString& InDocId) :
		FSLOwlDoc(InDocPrefix, InDocOntologyName, InDocId)
	{}

	// Destructor
	~FSLOwlExperiment() {}

	// Add timepoint individual value
	void RegisterTimepoint(const float Timepoint)
	{
		RegisteredTimepoints.AddUnique(Timepoint);
	}

	// Add individual instalce value
	bool RegisterObject(USLBaseIndividual* BI)
	{
		// Avoid logging the same individual multiple times
		bool bIsAlreadyInSet = false;
		RegisteredObjects.Add(BI, &bIsAlreadyInSet);
		return bIsAlreadyInSet;
	}

	// Create and add experiment node individual
	void AddExperimentIndividual(const TArray<FString>& SubActionIds, const FString& SemMapId, const FString& TaskId)
	{
		const FSLOwlPrefixName OwlNI("owl", "NamedIndividual");
		const FSLOwlPrefixName RdfAbout("rdf", "about");
		const FSLOwlPrefixName RdfType("rdf", "type");
		const FSLOwlPrefixName KrPerformedInMap("knowrob", "performedInMap");
		const FSLOwlPrefixName KrPerformedTask("knowrob", "performedTask");
		const FSLOwlPrefixName KrSubAction("knowrob", "subAction");
		const FSLOwlPrefixName KrStartTime("knowrob", "startTime");
		const FSLOwlPrefixName KrEndTime("knowrob", "endTime");
		const FSLOwlPrefixName RdfResource("rdf", "resource");
		const FSLOwlAttributeValue ExperimentId(Prefix, Id);

		// Create experiment individual
		ExperimentIndividual.Name = OwlNI;
		ExperimentIndividual.AddAttribute(FSLOwlAttribute(RdfAbout, ExperimentId));
		ExperimentIndividual.AddChildNode(FSLOwlNode(RdfType, FSLOwlAttribute(
			RdfResource, FSLOwlAttributeValue("knowrob", "AmevaExperiment"))));

		// Add semantic map id
		ExperimentIndividual.AddChildNode(FSLOwlNode(KrPerformedInMap, FSLOwlAttribute(
			RdfResource, FSLOwlAttributeValue(Prefix, SemMapId))));

		// Add executed task id
		ExperimentIndividual.AddChildNode(FSLOwlNode(KrPerformedTask, FSLOwlAttribute(
			RdfResource, FSLOwlAttributeValue(Prefix, TaskId))));

		// Add start and end time
		if (RegisteredTimepoints.Num() > 2)
		{
			float StartTime = RegisteredTimepoints[0];
			const FString StartTimeId = "timepoint_" + FString::SanitizeFloat(StartTime);
			ExperimentIndividual.AddChildNode(FSLOwlNode(KrStartTime,
				FSLOwlAttribute(RdfResource, FSLOwlAttributeValue("log", StartTimeId))));

			float EndTime = RegisteredTimepoints.Last();
			const FString EndTimeId = "timepoint_" + FString::SanitizeFloat(EndTime);
			ExperimentIndividual.AddChildNode(FSLOwlNode(KrEndTime,
				FSLOwlAttribute(RdfResource, FSLOwlAttributeValue("log", EndTimeId))));
		}

		// Add subactions
		for (const auto& SubActionId : SubActionIds)
		{
			ExperimentIndividual.AddChildNode(FSLOwlNode(KrSubAction, FSLOwlAttribute(
				RdfResource, FSLOwlAttributeValue("log", SubActionId))));
		}

		ExperimentIndividual.Comment = "Experiment Individual " + Id;

		// Add the experiment to the document individuals
		AddIndividual(ExperimentIndividual);
	}

	// Add time / object individuals to document
	void AddTimepointIndividuals()
	{
		CreateTimepointIndividuals();
		if (TimepointIndividuals.Num() > 0)
		{
			TimepointIndividuals[0].Comment = "Timepoint Individuals";
			AddIndividuals(TimepointIndividuals);
		}
	}

	// Add object individuals
	void AddObjectIndividuals()
	{
		CreateObjectIndividuals();
		if (ObjectIndividuals.Num() > 0)
		{
			ObjectIndividuals[0].Comment = "Object Individuals";
			AddIndividuals(ObjectIndividuals);
		}
	}

private:
	// Create timepoint individuals from the registered timepoints
	void CreateTimepointIndividuals()
	{
		// Individuals already created
		if (TimepointIndividuals.Num() > 0)
		{
			UE_LOG(LogTemp, Warning, TEXT("%s::%d Timepoint individuals already created.."), *FString(__FUNCTION__), __LINE__);
			return;
		}

		// Sort timestamps
		//RegisteredTimepoints.Sort([](const float& A, const float& B) { return A < B; });
		RegisteredTimepoints.StableSort();

		// Create and add time individuals
		for (float Ts : RegisteredTimepoints)
		{
			TimepointIndividuals.Add(CreateTimepointIndividual("log", Ts));
		}
	}

	// Create timepoint individuals from the registered timepoints
	void CreateObjectIndividuals()
	{
		// Individuals already created
		if (ObjectIndividuals.Num() > 0)
		{
			UE_LOG(LogTemp, Warning, TEXT("%s::%d Object individuals already created.."), *FString(__FUNCTION__), __LINE__);
			return;
		}

		// Create and add time individuals
		for (const auto& BI : RegisteredObjects)
		{
			ObjectIndividuals.Add(CreateObjectIndividual("log", BI->GetIdValue(), BI->GetClassValue()));
		}
	}

public:
	/* Static helper functions */
	// Create a timepoint individual
	static FSLOwlNode CreateTimepointIndividual(const FString& InDocPrefix, const float Timepoint)
	{
		// Prefix name constants
		const FSLOwlPrefixName RdfAbout("rdf", "about");
		const FSLOwlPrefixName OwlNI("owl", "NamedIndividual");
		const FString Id = "timepoint_" + FString::SanitizeFloat(Timepoint);
		FSLOwlNode Individual(OwlNI, FSLOwlAttribute(RdfAbout, FSLOwlAttributeValue(InDocPrefix, Id)));
		Individual.AddChildNode(FSLOwlNode::CreateResourceProperty("knowrob", "Timepoint"));
		return Individual;
	}

	// Create an object individual
	static FSLOwlNode CreateObjectIndividual(const FString& InDocPrefix, const FString& InId, const FString& InClass)
	{
		// Prefix name constants
		const FSLOwlPrefixName RdfAbout("rdf", "about");
		const FSLOwlPrefixName OwlNI("owl", "NamedIndividual");

		FSLOwlNode Individual(OwlNI, FSLOwlAttribute(RdfAbout, FSLOwlAttributeValue(InDocPrefix, InId)));
		Individual.AddChildNode(FSLOwlNode::CreateResourceProperty("knowrob", InClass));
		return Individual;
	}
};


text:
import pytest

from noscrapy.selectors import GroupSelector

GET_DATA = {
    'text':
        (GroupSelector('a', css='p'), '
a

b
', [{'a': ({'a': 'a'}, {'a': 'b'})}]),
    'href':
        (GroupSelector('a', css='a', extract='href'),
        'ab',
        [{'a': ({'a': 'a', 'a-href': 'http://aa/'}, {'a': 'b', 'a-href': 'http://bb/'})}]),
    'empty':
        (GroupSelector('a', css='p'), '', [{'a': ()}]),
}
@pytest.mark.parametrize('selector,html,expected', list(GET_DATA.values()), ids=list(GET_DATA))
def test_group_selector_get_data(selector, html, expected):
    assert list(selector.get_data(html)) == expected

def test_group_selector_columns():
    assert GroupSelector('id', css='div').columns == ('id',)
    assert GroupSelector('id', css='div', extract='href').columns == ('id',)


text:
'use strict';

Router.configure({
  layoutTemplate: 'masterLayout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'pageNotFound',
  yieldTemplates: {
    nav: {to: 'nav'},
    footer: {to: 'footer'},
  }
});

Router.route('/', {
  name: 'home',
});

Router.route('/howitworks', {
  name: 'howItWorks',
});

Router.route('/accounts', {
  name: 'accounts',
  onBeforeAction: function(){
    if (!Meteor.loggingIn() && !Meteor.userId()) {
      Router.go('home');
    }
    else {
      this.next();
    }
  },
});

Router.route('/log/:_id', {
  name: 'log.show',
  template: 'Log'
});

Router.route('/hooks', {
  name: 'hooks',
  conroller: 'HooksController'
});

Router.route('/subscriptions', {
  name: 'subscriptions',
  conroller: 'SubscriptionsController'
});

Router.route('/publish', function () {
  // NodeJS request object
  var request = this.request;

  // NodeJS response object
  var response = this.response;

  // Asks to process the request
  Meteor.call('processPublishRequest', request.body, function(err){
    // Checks if some error occurred...
    if (err) {
      console.dir(err);
      // ...and in case it was, denies the request signalling the error
      response.writeHead(err.error);
      response.end(err.reason);
    }
    else {
      // Aknowledges the request in case of no error
      response.end();
    }
  });
}, {where: 'server'});


text:
<!DOCTYPE html>

  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
  <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">
  <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">

  <title>Mac install MySQL</title>

Hasan Setiawan

Write, write, write give your wings on code!

      Follow me on GitHub

Mac install MySQL

          This procedure explains how to install MySQL using Homebrew on macOS Sierra 10.12

          At this time of writing, Homebrew has MySQL version 5.7.15 as default formulae in its
          main repository :

              Enter the following command : $ brew info mysql

              Expected output: mysql: stable 5.7.15 (bottled)

          To install MySQL enter : $ brew install mysql

          Additional configuration

          Homebrew

Install brew services first : $ brew tap homebrew/services

Load and start the MySQL service : $ brew services start mysql.
            Expected output : Successfully started mysql (label: homebrew.mxcl.mysql)

Check of the MySQL service has been loaded : $ brew services list 1

Verify the installed MySQL instance : $ mysql -V.
            Expected output : Ver 14.14 Distrib 5.7.15, for osx10.12 (x86_64)

          MySQL

          Open Terminal and execute the following command to set the root password:
          mysqladmin -u root password 'yourpassword'

          Important : Use the single 'quotes' to surround the password and make sure to select a strong password!
          ###Database Management To manage your databases, I recommend using Sequel Pro, a MySQL management tool designed for macOS.
          Current version available: 1.1.2

          #####Comments 1 The brew services start mysql - instruction is equal to :

$ ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

This page was generated by GitHub Pages using the Architect theme by Jason Long.

Back


text:
In this step, our goal is to extract the information from the header of
at least one NIfTI (I'm just going to use nifti from now on) format file.
We have to learn some other things first, though.

## Creating new functions

In the last episode, we saw some ways to create folders and move around
in them from within our Python program.  The way we left things, we had
written Python in a `try...except` block that we could use to create
a new folder that would also do the right thing if one existed (or mostly
the right thing).  To use it more than once, we have to copy a bunch of
lines around.  If we do that, we are making it easy to introduce typos
and other kinds of error into our program, so we're going to turn that
into something we can reuse by typing `mk_my_dir()`.  Before we get to
that, we need to know how to write a new function.

### Writing functions, part 1

Simple functions just do something.  They don't take any input and they
don't produce any output.  One example of a function like that is the
`sys.exit` function that we imported in the last episode as `bail_out`
(mostly to show you how to import single functions from a library and
how to rename them).  We _define_ functions using the `def` statement,
and here's an example.

```python
def my_world():
    print("My world, and welcome to it.")
```

Just the `def` statement, the name of the new function (with parentheses),
and what it does.  If you do that from the Python prompt, you get

```python
>>> def my_world():
...     print("My world, and welcome to it.")
...
>>> my_world()
My world, and welcome to it.
```

You might use something like that to print the name and version of your
program when it starts, for example, so that's not an entirely useless
example.

We can define a function called, say `up_one()` that simply changes up
one directory level.  We can only do that because the name for "up one level"
is always defined and is always the same.

```python
def up_one():
    parent = '..'
    os.chdir(parent)
```

What happens if `os` wasn't imported?  Try it.  I got

```python
>>> up_one()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in up_one
NameError: global name 'os' is not defined
```

This is where something called `try` can come in handy.  It's often
referred to as `try...except`, because not only do you tell it what
to try, you tell it what to do if it takes exception with you.  Notice
in the above, that the last line says: `NameError: global name 'os' not
defined`.  The _exception type_ is `NameError`, and the exception
message is the rest.  When we want Python to try something, we then
tell it what to do in the case of an exception, and we can do different
things depending on the type of exception.

```python
try:
    os.chdir('..')
except NameError:
    import os
    os.chdir('..')
except:
    print("Something really bad happened, man!")
```

We can get fancier with our functions by making them able to read values
when we use them.  Consider this definition,

```python
def my_something(gizmo):
    print("My {} is mine, not yours!").format(gizmo)
```
```python
>>> my_something('heart')
My heart is mine, not yours!
```

Another place where `try...except` is useful is checking to make sure
that the right kind of value was given to a function.   For example,

```python
>>> def my_calc(x):
...      return x / 2.0
...
>>> my_calc(2)
1.0
>>> my_calc('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in my_calc
TypeError: unsupported operand type(s) for /: 'str' and 'float'
```

So, we could make that function less _fragile_ if we put something
in to test for the type of variable.

```python
>>> def my_calc(x):
...     try:
...         return x/2.0
...     except TypeError:
...         print("Give me a number!")
...         return float('NaN')
...
>>> my_calc('a')
Give me a number!
nan
>>> my_calc(4)
2.0
```

That `float('NaN')` should be recognizable to people who have used
Matlab.  It's Not A Number.  We return it so that, if we were saving
the result of `my_calc()`, it would cause the right kind of error if
it were used later.

Being able to give a function something to work on is very useful.
Boy, howdy, is it!

## Finally we get to an image

Go to

http://nipy.org/nibabel/coordinate_systems.html

and download `someones_epi.nii.gz`

http://nipy.org/nibabel/_downloads/someones_epi.nii.gz

We will assume that it will go into the `Downloads` folder and
be loadable from there.

Here is an example of reading an `.nii` file (and some other
things).  This presumes you're on a machine that has `nibabel`
installed.

```python
>>> import nibabel as nib
>>> epi_img = nib.load('Downloads/someones_epi.nii.gz')
>>> epi_img_data = epi_img.get_data()
>>> epi_img_data.shape
>>> epi_img_header = epi_img.header
>>> print(epi_img_header)
<class 'nibabel.nifti1.Nifti1Header'> object, endian='<'
sizeof_hdr      : 348
data_type       :
db_name         :
extents         : 0
session_error   : 0
regular         :
dim_info        : 0
dim             : [ 3 53 61 33  1  1  1  1]
intent_p1       : 0.0
intent_p2       : 0.0
intent_p3       : 0.0
intent_code     : none
datatype        : uint8
bitpix          : 8
slice_start     : 0
pixdim          : [ 1.  3.  3.  3.  1.  1.  1.  1.]
vox_offset      : 0.0
scl_slope       : nan
scl_inter       : nan
slice_end       : 0
slice_code      : unknown
xyzt_units      : 2
cal_max         : 0.0
cal_min         : 0.0
slice_duration  : 0.0
toffset         : 0.0
glmax           : 0
glmin           : 0
descrip         :
aux_file        :
qform_code      : mni
sform_code      : mni
quatern_b       : 0.149438127875
quatern_c       : -0.0
quatern_d       : -0.0
qoffset_x       : -78.0
qoffset_y       : -76.0
qoffset_z       : -64.0
srow_x          : [  3.   0.   0. -78.]
srow_y          : [  0.           2.86600947  -0.88656062 -76.        ]
srow_z          : [  0.           0.88656062   2.86600947 -64.        ]
intent_name     :
magic           : n+1
```

Is that science?!

So, quit your regular Python, and instead start your IPythons.
And, in addition, your IPython has to be able to open windows.
That should Just Work if you are on the Skills machine and using
VNC.

IPython uses a very different prompt.

```python
In [1]:
```

IPython is also notorious for being badly behaved if you try to
copy and paste any indented Python commands into it.  If you want
to do that, you can use what is called a _magic_ (or maybe _magik_).

First, here is the code that we want to paste.  Copy just to the
blank line, then paste it.

```python
import matplotlib.pyplot as plt

def show_slices(slices):
   """ Function to display row of image slices """
   fig, axes = plt.subplots(1, len(slices))
   for i, slice in enumerate(slices):
       axes[i].imshow(slice.T, cmap="gray", origin="lower")

slice_0 = epi_img_data[26, :, :]
slice_1 = epi_img_data[:, 30, :]
slice_2 = epi_img_data[:, :, 16]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image")
```
It will either double the size of the indents, or it will go
totally wacko with the indents.  To be safe, you use

```python
In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def show_slices(slices):
:   """ Function to display row of image slices """
:   fig, axes = plt.subplots(1, len(slices))
:   for i, slice in enumerate(slices):
:       axes[i].imshow(slice.T, cmap="gray", origin="lower")
:--
In [2]:
```

The `%` indicates it is magic.  Trust me, just do this.  Especially
if the chunk you're pasting has many indents.

We saw the full header of an image above, but it's much more likely
that you will only want some part of the header.  Here is some python
that will print just the description from the header of an
image that is included with `nibabel`.

```python
import os
import numpy as np
from nibabel.testing import data_path
example_file = os.path.join(data_path, 'example4d.nii.gz')
import nibabel as nib
img = nib.load(example_file)
header = img.header
header['descrip']
print(header['descrip'])
```

Note, that, in the example above, we're using that
`os.path.join()` function to create a path that will work whether
we're on Linux, Mac, or Windows.  We're also renaming the libraries
as we import them (or functions from them).  All of the muck at the
top is so we can do `img = nib.load(example_file)`, which is how
you read an image into Python.  The image has two parts, a header,
which we've seen, and data.  We extract the header from the `img` and
put it into its own variable.

See http://nipy.org/nibabel/nibabel_images.html

## Python dictionaries

We've seen that lists in Python can be used to collect multiple items into
one place and then use them, one after another.  An individual item can
only be referred to in a list by its position, commonly called its _index_.

Sometimes that's not such a hot idea.  One example where something else is
desirable is when the number of items is different depending on circumstances,
so the number of items changes, leaving gaps.  In one list, it might be
that the fourth item is the same as the sixth item in another list.  Python
uses _dicitionaries_ as the way to give each element a name -- the _key_ --
and that is used to access the _value_ associated with it.  They are sometimes
called _associative arrays_, and smattering your conversation with references
to _key-value pairs_ shows you're cool.

Just above, we saw how to get the values of items in a dictionary; like this

```python
print(header['descrip'])
```

In this case, the dictionary component is hidden behind something else, a
NiPy image object, but that's what it is.  In the case above, `header` would
be the name of the dictionary variable, and `descrip` is the name of the
entry.  These are very much like database fields.  OK, that's how we get
stuff out of one, how do we get stuff into one?  First, we need to tell
Python that we want a dictionary.

```python
header = {}
```
or
```python
header = dict()
```

Once it is created, you add things to it by specifying the key (name) in the
same way you would specify an index to a list -- in square brackets.  Suppose
we have the following information about a how images for a study were acquired.

> We obtained 146 contiguous echo planar imaging (EPI) whole-brain functional
volumes (TR=2000 ms; TE=30 ms; flip angle=80, 40 slices, matrix=64x64;
FOV=192 mm; acquisition voxel size=3x3x4mm) during each of the two flanker
task blocks.

> A high-resolution T1-weighted anatomical image was also acquired using a
magnetization prepared gradient echo sequence (MPRAGE, TR=2500 ms;
TE= 3.93 ms; TI=900 ms; flip angle=8; 176 slices, FOV=256 mm).

Now we want to put some of that into a dictionary so we can refer to it.

```python
>>> EPI_info = dict()
>>> EPI_info['TR'] = 2000
>>> EPI_info['TE'] = 30

>>> print(EPI_info['TE'])
30
>>> type(EPI_info['TE'])
int
```

That's all very well and good, so long as you have a record of what the
keys are somewhere, right?  You can get the keys present in a list with

```python
for key in EPI_info:
    print(key)
TE
TR
```

Note, though that the keys are not sorted, nor are they guaranteed to be
in any particular order.  If you want the keys to be sorted, you must
refer to them with `sorted(EPI_info.keys())`.

OK, your turn.  Write a little program that will created the `EPI_info`
dictionary above and print a list of the sorted keys and their values.

Project:  Get header information from `.nii` files in several folders with
one program.  Your program should change to at least one folder different
from where it started, read at least two `.nii` files, and print the `dim`
and `descrip` fields from the header.


text:
python app.py

cmd


text:
/*
  This abstraction presents the Socket.io (and potentially other
  transports) as an EventEmiiter.  It takes care of forwarding
  the messages between the emitter and the message transport.

  API:
  To have the history sent, prefix the topic name that is being
  subscribed to with 'withHistory'.
*/
(function() {
  var root = this;

  var EventEmiiterStoreAndForward = function(coveredEventEmitter) {
    var self = this;
    this.eventCache = {};
    var original_on = coveredEventEmitter.on;

    coveredEventEmitter.withHistory = {};

    coveredEventEmitter.withHistory.on = function(aType,aListener){
      if (self.eventCache[aType]!==undefined){
        var d = self.eventCache[aType];
        aListener.call(d[0],d[1],d[2],d[3],d[4],d[5]);
      }
      original_on.call(coveredEventEmitter, aType, aListener);
    };

    coveredEventEmitter.onAny(function(data1, data2, data3, data4, data5){
      self.eventCache[this.event]=[this,data1,data2,data3,data4,data5];
    });

    return coveredEventEmitter;
  }

  if( typeof exports !== 'undefined' ) {
    if( typeof module !== 'undefined' && module.exports ) {
      exports = module.exports = EventEmiiterStoreAndForward
    }
    exports.EventEmiiterStoreAndForward = EventEmiiterStoreAndForward
  }
  else {
    root.EventEmiiterStoreAndForward = EventEmiiterStoreAndForward
  }

}).call(this); //on the bowser, this is the window object


text:
/etc/init.d/kube-proxy stop
/etc/init.d/kube-proxy start

echo "waiting a minute for startup"
sleep 60

max_seconds=10

while true; do
  if ! curl -m ${max_seconds} -f -s http://127.0.0.1:10249/healthz > /dev/null; then
    echo "kube-proxy failed!"
    exit 2
  fi
  sleep 10
done


text:
class Link < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end


text:
<?php

    namespace Slashworks\AppBundle\Model;

    use Slashworks\AppBundle\Model\om\BaseRemoteAppQuery;

    /**
     * Class RemoteAppQuery
     *
     * @package Slashworks\AppBundle\Model
     */
    class RemoteAppQuery extends BaseRemoteAppQuery
    {

    }


text:
package com.njkremer.Sqlite.utils;

import org.springframework.aop.support.AopUtils;

public class SqliteUtils {
    public static Class<?> getClass(Object object) {
        return AopUtils.getTargetClass(object);
    }

    public static String capitalize(String word) {
        return word.substring(0, 1).toUpperCase() + word.substring(1);
    }

    public static String lowercase(String word) {
        return word.substring(0, 1).toLowerCase() + word.substring(1);
    }

    public static boolean isEmpty(Object object) {
        if(object == null) {
            return true;
        }
        if (object instanceof String) {
            return ((String) object).trim().length() == 0;
        }
        else if (object instanceof Float) {
            return ((Float) object) == 0.0f;
        }
        else if (object instanceof Integer) {
            return ((Integer) object) == 0;
        }
        else if (object instanceof Long) {
            return ((Long) object) == 0l;
        }
        else if (object instanceof Double) {
            return ((Double) object) == 0.0d;
        }
        else if (object instanceof Boolean) {
            return ((Boolean) object) == false;
        }
        return false;
    }
}


text:
This directory contains a number of tutorials that show off various aspects of
[Caliban](https://github.com/google/caliban).

The `basic` directory contains the code for the ["Getting Started with
Caliban"](https://github.com/google/caliban#getting-started-with-caliban)
tutorial on the main page of [Caliban's github
repository](https://github.com/google/caliban).

More coming soon!


text:
package bi.meteorite.ui;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		//nothing to do here ...
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.getWriter().println(
				"Filter was there before. Time: " + new Date().toString());
		chain.doFilter(request, response);
		response.getWriter().println(
				"Filter was there after. Time: " + new Date().toString());
		response.getWriter().close();
	}

	public void destroy() {
	}
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Collections.Generic.Comparer`1<System.DateTime>
struct Comparer_1_t793694272;
// System.Object
struct Il2CppObject;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object837106420.h"

// System.Void System.Collections.Generic.Comparer`1<System.DateTime>::.ctor()
extern "C"  void Comparer_1__ctor_m320273535_gshared (Comparer_1_t793694272 * __this, const MethodInfo* method);
#define Comparer_1__ctor_m320273535(__this, method) ((  void (*) (Comparer_1_t793694272 *, const MethodInfo*))Comparer_1__ctor_m320273535_gshared)(__this, method)
// System.Void System.Collections.Generic.Comparer`1<System.DateTime>::.cctor()
extern "C"  void Comparer_1__cctor_m856448782_gshared (Il2CppObject * __this /* static, unused */, const MethodInfo* method);
#define Comparer_1__cctor_m856448782(__this /* static, unused */, method) ((  void (*) (Il2CppObject * /* static, unused */, const MethodInfo*))Comparer_1__cctor_m856448782_gshared)(__this /* static, unused */, method)
// System.Int32 System.Collections.Generic.Comparer`1<System.DateTime>::System.Collections.IComparer.Compare(System.Object,System.Object)
extern "C"  int32_t Comparer_1_System_Collections_IComparer_Compare_m3554860588_gshared (Comparer_1_t793694272 * __this, Il2CppObject * ___x, Il2CppObject * ___y, const MethodInfo* method);
#define Comparer_1_System_Collections_IComparer_Compare_m3554860588(__this, ___x, ___y, method) ((  int32_t (*) (Comparer_1_t793694272 *, Il2CppObject *, Il2CppObject *, const MethodInfo*))Comparer_1_System_Collections_IComparer_Compare_m3554860588_gshared)(__this, ___x, ___y, method)
// System.Collections.Generic.Comparer`1<T> System.Collections.Generic.Comparer`1<System.DateTime>::get_Default()
extern "C"  Comparer_1_t793694272 * Comparer_1_get_Default_m2450725187_gshared (Il2CppObject * __this /* static, unused */, const MethodInfo* method);
#define Comparer_1_get_Default_m2450725187(__this /* static, unused */, method) ((  Comparer_1_t793694272 * (*) (Il2CppObject * /* static, unused */, const MethodInfo*))Comparer_1_get_Default_m2450725187_gshared)(__this /* static, unused */, method)