text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import com.google.sps.data.ParseMails;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* This class gets an email and a postcard link from the client
* and then sends a message to it's receiver.
**/

@WebServlet("/mail")
public class MailServlet extends HttpServlet {

  static final String MSG_BODY = "...";
  static final String SUBJECT = "You've received a postcard!";
  static final String SENDER = "GPostcard";
  static final String RECEIVER = "You";
  static final String POSTCARD_CONTAINER = "
";

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();

    // Only logged-in users can post messages
    if (!userService.isUserLoggedIn()) {
      response.sendRedirect("/index.html");
      return;
    }

    String email = userService.getCurrentUser().getEmail();
    String title = request.getParameter("title");
    String message = request.getParameter("message");
    String image = request.getParameter("image");

    String mails = request.getParameter("mail");

    String resp = sendMultipartMail(email, mails, title, message, image);

    response.setContentType("text/html;");
    response.getWriter().println(resp);
  }

/**
* This function creates an email and sends it to the user
**/

  private String sendMultipartMail(String from, String mails, String title, String userMessage, String image) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {
      ParseMails parseMails = new ParseMails(mails);
      List<String> mailsList = parseMails.getMails();

      for (String to:mailsList) {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, SENDER));
        message.addRecipient(Message.RecipientType.TO,
                       new InternetAddress(to, RECEIVER));
        message.setSubject(SUBJECT);
        message.setText(MSG_BODY);

        /*
         * Problem: Sometimes application/x-www-form-urlencoded does NOT send the entire string.git
         * First solution: Use Java hard-coded html elements, instead of sending them from the front-end.
         * TODO: Try to send JSON insted of application/x-www-form-urlencoded.
        **/
        final String htmlBody = POSTCARD_CONTAINER +
              "

" +
              "

" +
              "

" +
              "

" +
              "

" +
              "

" +
              "
" +
              "	" +
              "

" +
              "

" +
              "
" +
              userMessage + "

";

        byte[] attachmentData = null;
        Multipart mp = new MimeMultipart();

        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        mp.addBodyPart(htmlPart);

        message.setContent(mp);

        Transport.send(message);
      }

    } catch (AddressException e) {
      System.err.println("Not existing address");
      return "Not existing address";
    } catch (MessagingException e) {
      System.err.println("Something went wrong:(");
      return "Something went wrong:(";
    } catch (UnsupportedEncodingException e) {
      System.err.println("Something went wrong:(");
      return "Something went wrong:(";
    }
    return "Your postcard has been sent!";
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revista Chilena Hist. Nat. 40:227. 1936

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package ca.utoronto.civ.its.galapagos.operators.topologies;

import java.util.Hashtable;

import ca.utoronto.civ.its.galapagos.ParamException;
import ca.utoronto.civ.its.galapagos.ParamTreeNode;
import ca.utoronto.civ.its.galapagos.templates.Topology;

public class StaticTopology extends Topology
{
    private Hashtable targetHash;

    public void setParameters(ParamTreeNode params) throws ParamException
    {
        targetHash = new Hashtable();

        String popId;

        for(int i = 0; i < params.getNumChildren("target"); i++)
        {
            ParamTreeNode theTargetNode = params.getChild("target", i);
            popId = theTargetNode.getChild("populationid").getString();
            targetHash.put(popId, new Integer(theTargetNode.getChild("nummigrants").getString()));
        }
    }

    public Hashtable nextTargetHash()
    {
        return targetHash;
    }
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace HttpNet.Tests
{
    [TestClass]
    public class HttpRequestTests
    {
        [TestMethod]
        public void Can_GET_URL()
        {
            var request = new HttpNet.HttpRequest();
            var response = request.Get("http://httpbin.org/get");

            //Assert.IsFalse(string.IsNullOrEmpty(response.Text));
        }
    }
}


text:
class CreatePlaces < ActiveRecord::Migration[5.0]
  def change
    create_table :places do |t|

      t.string :name
      t.text :description
      t.string :address

      t.timestamps
    end
  end
end


text:
class AddingIndexesForDynamicAttributes < ActiveRecord::Migration
  def self.up
    add_index :dynamic_attribute_values, :dynamic_attribute_id
    add_index :dynamic_attribute_values, :contact_id
  end

  def self.down
    remove_index :dynamic_attribute_values, :dynamic_attribute_id
    remove_index :dynamic_attribute_values, :contact_id
  end
end


text:
category: HostGroup
apiurl: '/api/v1/hostgroup/host'
title: "Unbind a Host on HostGroup"
type: 'PUT'
sample_doc: 'hostgroup.html'
layout: default
---

* [Session](#/authentication) Required
* 如果使用者不是 Admin 只能对创建的hostgroup做操作

### Request
```{
  "hostgroup_id": 343,
  "host_id": 9312
}```

### Response

```Status: 200```
```{"message":"unbind host:9312 of hostgroup: 343"}```


text:
package com.example.android.uamp.ui;

import android.support.v4.media.MediaBrowserCompat;

public interface MediaBrowserProvider {
    MediaBrowserCompat getMediaBrowser();
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="30dp"
        android:height="30dp"
        android:viewportHeight="24.0"
        android:viewportWidth="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z"/>
</vector>


text:
const debug = require('debug')('app:bin:dev-server');
const project = require('../config/project.config');

const app = require('../server/app.js');

const server = app.listen(project.server_port);

server.on('listening', () => debug(`Server is now running at http://localhost:${project.server_port}.`));


text:
import abc
import logging
import matplotlib as mlt
import matplotlib.pyplot as plt
import networkx as nx
import os

log = logging.getLogger('analyzer')

class Analyzer(object):
    """Abstract base class for model analyzers."""
    __metaclass__ = abc.ABCMeta

    def __init__(self, model):
        """Initializes a new instance of the Analyzer class."""

        self.model = model
        self._graph = None

    @property
    def graph(self):
        """Returns a NetworkX graph model."""

        if self._graph is None:
            self._graph = self._build_graph(self.model)
        return self._graph

    def _build_graph(self, model):
        log.debug('Building NetworkX graph...')
        graph = nx.DiGraph()
        for node in model.nodes:
            graph.add_node(node.id, size=node.size)

        for node in model.nodes:
            for conn in node.connections:
                graph.add_edge(node.id, conn)

        log.debug('NetworkX graph size: nodes=%d edges=%d', graph.number_of_nodes(), graph.number_of_edges())
        return graph

class Writer(Analyzer):
    """A graph model writer"""

    def __init__(self, model):
        """Initializes a new instance of the Writer class."""
        super(Writer, self).__init__(model)

    def write(self, path, data_format='dot'):
        """Writes the underlying graph model to a specific file."""

        if data_format == 'dot':
            nx.write_dot(self.graph, path)
        elif data_format == 'gml':
            nx.write_gml(self.graph, path)
        elif data_format == 'graphml':
            nx.write_graphml(self.graph, path)
        else:
            raise AssertionError('Invalid format: %s' % data_format)

class Plotter(Analyzer):
    """A graph plotter."""

    node_colors = ['#ffd070', '#e6ff6f', '#ff886f', '#6f9eff', '#cf6fff']

    def __init__(self, model):
        """Initializes a new instance of the Plotter class."""
        super(Plotter, self).__init__(model)

    def plot(self, **kwargs):
        """Plots the underlying graph."""

        plt.figure(facecolor='#fefefe', dpi=80, frameon=True)
        plt.axis('off')

        try:
            positions = nx.graphviz_layout(self.graph)
        except ImportError as err:
            log.info('Graphviz not available: error=%s', err)
            log.info('Falling back to spring layout...')
            positions = nx.spring_layout(self.graph)
        #FIXME: Caused by bin/coffea in some cases
        except TypeError as err:
            log.warn('Graphviz layout failed: error=%s', err)
            log.warn('Falling back to spring layout...')
            positions = nx.spring_layout(self.graph)

        if 'calc_node_size' in kwargs and kwargs['calc_node_size']:
            node_size = self._node_size_vector
            if node_size is None:
                node_size = 300
        else:
            node_size = 300

        log.debug('Drawing nodes...')
        nx.draw_networkx_nodes(self.graph, positions,
                               node_color=self.node_colors,
                               node_size=node_size,
                               alpha=0.8)

        log.debug('Drawing edges...')
        nx.draw_networkx_edges(self.graph, positions,
                               edge_color='#666666',
                               alpha=0.75)

        log.debug('Drawing labels...')
        nx.draw_networkx_labels(self.graph,positions,
                                font_color='#222222',
                                font_family='courier new',
                                font_weight='bold')

        log.debug('Plotting graph...')
        try:
            filename = kwargs['filename']
            plt.savefig(filename, bbox_inches='tight')
        except KeyError:
            plt.show()

    @property
    def _node_size_vector(self):
        log.debug('Calculating size vector...')
        size_vect = []
        for _, attrs in self.graph.nodes_iter(data = True):
            if 'size' in attrs:
                size_vect.append(attrs['size'])
            else:
                # External node may not have a size attribute
                size_vect.append(0)

        max_val = max(size_vect)
        if max_val != 0:
            log.debug('Normalizing size vector...')
            size_vect = [200 + s / (max_val*1.0)*800 for s in size_vect]
        else:
            size_vect = None

        return size_vect


text:
title: 'Using RequireJS In WordPress'
comments: true
author: Kai Gittens
layout: post
meta-excerpt: Learn how to use RequireJS in WordPress. Includes a walk-through of how RequireJS works and how WordPress manages JavaScript internally.
permalink: /requirejs-wordpress/
category: coding-best-practices
cat-name: "Code Tips"
has-home-img: require-wordpress.jpg
tags: [RequireJS, Wordpress, jQuery, AMD, javascript]
---
As mentioned in [my 2013 site redesign post](/site-redesign-2013/ "A walk-through of how kaidez.com was redesigned"), I started redesigning this site on top of [WordPress](http://wordpress.org/ "Go to WordPress.org") but eventually switched over to [Jekyll](http://jekyllrb.com/ "Go to the Jekyll blog engine site"). This was because my goal was to use [RequireJS](http://requirejs.org/ "Go to requirejs.org") to control all the site's JavaScript in a specific way, and WordPress kept me from doing this.

The issue: my RequireJS setup needed to treat [jQuery](http://jquery.com/ "Check out the jQuery library") as a dependency for certain code modules. But a default WordPress install includes jQuery, and WP needs to manage it and other internal JS files in a manner that benefits its entire ecosystem: a manner that imposed limits on what I wanted RequireJS to do.

*(Side note: this post is long so if you're looking for a quick answer for using RequireJS inside of WordPress, go to the ["How To Use jQuery, RequireJS & WordPress Together"](#jquery-requirejs-wordpress "How To Use jQuery, RequireJS & WordPress Together") section.)*

## Table of Contents
1. [Assumptions & Notes](#assumptions-notes)
2. [What Is RequireJS?](#what-is-requirejs)
3. [A RequireJS Example](#quick-requirejs-example)
4. [How I THOUGHT RequireJS Should Bring jQuery Into WordPress](#bring-jquery-into-wordpress)
5. [The RIGHT Way To Load jQuery Into WordPress](#load-js-into-wordpress)
6. [How To Use jQuery, RequireJS & WordPress Together](#jquery-requirejs-wordpress)
7. [RequireJS/AMD, WordPress & The Future?](#future-requirejs-amd-wordpress)
8. [Conclusion](#conclusion)

## Assumptions & Notes
I'm making a few assumptions:

The main assumption is that you understand WordPress beyond configuring it inside the Dashboard. This post discusses adding code to WordPress files so you should be comfortable doing this. You should also understand that adjusting code in WP is relatively easy when using the [WordPress Codex](http://codex.wordpress.org/) as a reference.

All my initial RequireJS/WordPress work was done inside a child theme, a well-defined WP best practice, so I'm assuming you know how to implement this. If not, [the Child Theme docs in the WordPress Codex](http://codex.wordpress.org/Child_Themes "How to create a child theme in WordPress") clearly describe how it's done.

RequireJS is relatively new when compared to WordPress so I do walk through the former more that the latter, but it's still only a walk-through. RequireJS can do much more than the tasks discussed in this post so I'm assuming that you're curious about RequireJS and have no problem reading a few things to better understand it, starting with the [RequireJS API docs](http://requirejs.org/docs/api.html "Read the RequireJS API").

Some notes...

This post should *not* be looked as my stating that "WordPress is bad." WordPress is awesome and I will continue to use it, but it was not the way to go in order to meet the RequireJS-related goal I set for myself with this redesign. I discuss this at great length in [my site redesign post](/site-redesign-2013/#jekyll "Read about why kaidez.com switched from WordPress to Jekyll").

When I started working on the redesign, I was working with WordPress version 3.5.2. I then left for Jekyll and since that time, WordPress has released versions 3.6 and 3.7, the latter being released shortly before this post's publish date.

TwentyTwelve was the default theme for 3.5.2, and was what my child theme was based upon.  Both 3.6 and 3.7 use TwentyThirteen as its default theme, which loads JavaScript onto a WP site differently from TwentyTwelve and previous themes.

I did test *some* RequireJS things in version 3.6/TwentyThirteen and did no testing in version 3.7 testing at all because it was released roughly three weeks before this post's publish date. So this post's point of view is from using RequireJS inside a 3.5.2/TwentyTwelve setup, but what really matters is how WordPress pre-installs JS libraries and plugins before the themes actually use them. That, I have tested across all the versions and themes mentioned: the pre-install process is the same all around.

And finally, there were some RequireJS things that I struggled with at both the beginning and end of the redesign. I pile a ton of gratitude onto [Cary Landholt](https://twitter.com/carylandholt "Visit Cary Landholt's Twitter page") for helping me through the struggles.  Spending some time going through [Cary's YouTube screencasts](http://www.youtube.com/user/carylandholt "Watch Cary Landholt's YouTube screencasts") is time well spent, particularly his RequireJS ones that are geared for beginners. Also, his [GitHub page](https://github.com/CaryLandholt "Visit Cary Landholt's GitHub page") is full of top-notch code samples.

## What Is RequireJS?
RequireJS is a script loader written in JavaScript that creates a dependency management system within your website or web app. It's based on the [Asynchronous Module Definition (AMD) specification](https://github.com/amdjs/amdjs-api/wiki/AMD) which defines a code pattern for loading JS files in an asynchronous, organized, non-blocking fashion.

Generally speaking, a RequireJS setup consists of two parts:

1. __A group of modules__: single units of JavaScript code that execute either a code block or a small group of closely-related code blocks. You can create multiple modules, with each module executing the code block(s).

2. __Configurations__: settings you pass to RequireJS so it can properly manage all the modules within your site or app, making sure everything works seamlessly.

The modules contain not only the code needed to run your task(s), but also lists the dependencies that this code needs to run the task(s). These dependencies are things like the core jQuery library and plugins

Based on the configurations, RequireJS asynchronously loads the modules and dependencies onto your site. Let's examine this further by looking at an example of how RequireJS works on kaidez.com.

## A RequireJS Example
This site's search functionality is powered by the [Tipue Search plugin for jQuery](http://www.tipue.com/search/ "Read more about Tipue Search"). It takes end-user searches and returns the search results based on the data in a JSON object containing the site content.

Tipue needs four separate JS files to work and should be listed in the following order on an HTML page:

1. `jquery.js`: the core jQuery library.
2. `tipuesearch_content.js`: the file that contains the JSON object with the site content.
3. `tipuesearch_set.js`: the file that sets rules for certain words inputed into the search field, rules such as "ignore words like 'the' and 'or' in search inputs".
4. `tipuesearch.js`: the core Tipue plugin code.

In the past, setting up this functionality usually meant placing all these files in `<script>` tags on your HTML page in the order above, then putting your custom Tipue code somewhere below them. RequireJS allows for an easier process.

First, we  add the only `<script>` tag we need...it should go as close to the bottom of the page as possible:
{% prism markup %}

{% endprism %}

The info in the `data-main` attribute refers to a file called `config.js` which contains the configurations. The `.js` is purposely left off  because RequireJS *always* assume that the info referenced in this attribute is a JavaScript file.

`require.js` refers to the file containing the core RequireJS code.

Both files are in a directory called `scripts`.

The configurations in our `config.js` file look like this:

{% prism javascript %}
// We're only talking about creating one module here but this is
// the config setup for creating multiple modules. This is
// what's being discussed because it's common practice to use
// multiple modules in a site/app build.  The process for
// configuring a single module is discussed over at:
// http://requirejs.org/docs/api.html#define.

requirejs.config({

  baseUrl: "/",

  deps: ["search"],

  paths: {
    jquery: "libs/jquery.min", // v.1.10.2
    tipue: "libs/tipuesearch.min",
    tipueset: "libs/tipuesearch_set",
    tipuesetContent: "libs/tipuesearch_content"
  },

  shim: {
    tipue: {
      deps: ["jquery"],
      exports: "tipue"
    }
  }
});
{% endprism %}

Let's break all this down...

{% prism javascript %}
requirejs.config({
...
});
{% endprism %}

We wrap our code in a JavaScript object that will pass our configurations to the core RequireJS code.

{% prism javascript %}
baseUrl: "/",
{% endprism %}

`baseURL` represents a relative reference to the location of all the JS files that RequireJS must manage. In this case, the location is the `scripts` folder.

*(Side note: I'm using a very simplified file structure in order to keep this post from being too long, but the RequireJS docs do outline some best practices in terms of organizing your code.  The [Load JavaScript Files section in the RequireJS docs](http://requirejs.org/docs/api.html#jsfiles "Go to the Load JavaScript Files section in the RequireJS docs") is the place to read up on this.)*
{% prism javascript %}
deps: ["search"],
{% endprism %}

`deps` is an array of all the dependencies for our site or app.  The dependencies are the code modules that we talked about and are really just `.js` files.  Therefore, the `search` that's mentioned in the array is referring to a file called `search.js` and will contain the code needed to make Tipue work on the site.  We'll get to that code shortly and to be clear, `search.js` is located in the `scripts` folder.

{% prism javascript %}
paths: {
  jquery: "libs/jquery.min", // v.1.10.2
  tipue: "libs/tipuesearch.min",
  tipueset: "libs/tipuesearch_set",
  tipuesetContent: "libs/tipuesearch_content"
},
{% endprism %}
`paths` is a JavaScript object that lists the dependencies for the items listed in the `deps` array...you can think of them as the "dependencies of the dependencies". These files are located in a directory called `libs` that's in our `scripts` folder.

As you can see, these are the previously-discussed four files that Tipue needs to function properly on our website. Also note that we're using jQuery 1.10.2: this will be important when we start talking about the last part of the configs.

{% prism javascript %}
shim: {
  tipue: {
    deps: ["jquery"],
    exports: "tipue"
  }
}
{% endprism %}

As previously-mentioned, RequireJS is based on the AMD spec which defines a code pattern for loading JS files asynchronously. JavaScript files containing this pattern are said to be "AMD-compliant."

If the dependency is not AMD-compliant, RequireJS must force it to be so. That's what's happening here in this `shim` setting.

`tipue` is a reference to our core Tipue plugin code that was defined in the `paths` object.  It's not AMD-compliant so it's shimmed in.

`deps` tells RequireJS that the shimmed-in file needs jQuery to work properly. `exports`, a core [Node.js](http://nodejs.org/ "Learn more about Node.js") concept, properly exposes the shimmed-in file to RequireJS so it can treat it as a dependency based on the AMD spec.

Both the `tipueset` and `tipuesetContent` files listed in `paths` are also not AMD-compliant; however, they're just providing support for `tipue` to do its job instead of executing code. In this instance, there's no need to shim them.

jQuery also doesn't need to be shimmed in. This is because we're using version 1.10.2 and [jQuery has been AMD-compliant since version 1.7](http://blog.jquery.com/2011/11/03/jquery-1-7-released/ "Read about jQuery's support for AMD").

Now that our configs are set, we need to create the code that runs our Tipue search functionality. This goes into the `search.js` file that we referred to earlier in our `deps` array and looks like this:

{% prism javascript %}
define(["jquery","tipuesetContent","tipueset","tipue"], function($, tipuesetContent, tipueset, tipue) {

  $("#tipue_search_input").tipuesearch({
    "show": 10,
    "showURL": false,
    "highlightEveryTerm": true
  });

});
{% endprism %}

The `define()` method first defines all the code's dependencies in the array, then passes them as parameters for use by a callback function. Note that they're listed in the order outlined above: RequireJS will load things in this order.

The callback function contains our custom code, which does the following tasks:

* It takes the returned search results and places them in a page element with an id of `tipue_search_input`
* It will "show" 10 results per page.
* it will not "show the URL" for each result.
* It will "highlight" whatever the search term was by bolding it.

Our code is done. When our HTML page loads into a browser, `scripts/require.js` looks at the configurations in `scripts/config` and notices the `deps: ["search"]` setting, which refers to `scripts/search.js`.  It then sees that `search` needs four files to work properly, all of which are listed in the `paths` object.

RequireJS loads these four files and `scripts/search.js` into the `<head>` tag, and in the proper order. If the `<script>` tag is placed as close to the bottom of the page as possible, all the files will usually load in a manner that doesn't slow down your site's/app's load time. The code in `scripts/search.js` executes after everything loads.

*(Side note: your project's RequireJS files can be concatenated and minified down to a single file, but discussing this is outside the scope of this post. The [RequireJS optimization docs](http://requirejs.org/docs/optimization.html "Learn about optimizing RequireJS") outline how to get this done. Plus, Cary Landholt has [a great YouTube screencast on RequireJS Optimization](http://www.youtube.com/watch?v=m6VNhqKDM4E, "Check out Cary Landholt's screencast on optimizing RequireJS").)*

This was the code that I wanted to integrate into WordPress...and  this was where I started running into problems. Understanding these problems "requires" an understanding a few things about WordPress.

## How I THOUGHT RequireJS Should Bring jQuery Into WordPress
While TwentyThirteen preloads jQuery and other JavaScript files into the site's HTML, the TwentyTwelve theme I was working with does not. I was fine with this because as the above example illustrates, you only need to load one `script` tag onto the page to get RequireJS working.

As mentioned in the beginning, a default WordPress install contains jQuery other internal JS files. So I figured that I would just bring jQuery into my RequireJS configs by pointing to where WordPress placed it during install via the `paths` object:

{% prism javascript %}
paths: {
  // This ignores the 'baseURL' setting, but works well for Wordpress
  http://kaidez.com/wp-includes/js/jquery/jquery.js,
  ...
}
{% endprism %}
This worked fine for my RequireJS setup but creates potential future problems inside of WordPress.

## The RIGHT Way To Load jQuery Into WordPress
The default WordPress install contains many JS file that are "registered," meaning that WP knows they exist but doesn't necessarily load them into the theme's HTML. jQuery is an unloaded registered file in TwentyTwelve so it can come into the HTML in one of two ways:

1. a WordPress plugin that needs jQuery loads it in during the plugin's install.
2. a WordPress PHP function called `wp_enqueue_script` loads it onto the page.  This needs to be hand-written and should be placed in a custom `functions.php` file in your child theme...read more about [wp_enqueue_script](http://codex.wordpress.org/Function_Reference/wp_enqueue_script "Read more about wp_enqueue_script") and [functions.php](http://codex.wordpress.org/Functions_File_Explained "Read more about functions.php")

Once a registered file is loaded in like this, WordPress knows not to install it again.  In other words, if jQuery loads into the HTML via either a plugin or `wp_enqueue_script`, subsequent plugins requiring jQuery won't install it and will just use the one already installed.

Looking at my code snippet above, I didn't use any of these two methods...I just referred to the file in the `paths` object. This meant that WordPress had absolutely NO idea that jQuery was already on the site.

As a result, if I installed a WordPress plugin requiring jQuery, WP would load it into the HTML, meaning there would be two jQuery files on my page and that's not good. I was 99.99999% sure that I wouldn't be using such plugins and this would be a non-issue, but I wasn't 100% sure.

## How To Use jQuery, RequireJS & WordPress Together
With the 3.5.2/ TwentyTwelve setup, the safest thing to do was to use `wp_enqueue_script` to bring jQuery into the HTML. The code for this would be placed in the just-mentioned `functions.php` file and would look like this:
{% prism markup %}
<?php
function my_scripts_method() {
  wp_enqueue_script( 'jquery' );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
{% endprism %}

This loaded jQuery onto my page while preventing jQuery duplicates from loading, but I wasn't sure how to integrate this setup with my RequireJS functionality.

I surfed the web awhile looking for an answer, eventually posting something on RequireJS' GitHub Issue Tracker. It was at that point that RequireJS creator [James Burke gave me an answer](https://github.com/jrburke/requirejs/issues/622 "James Burke shows how to use RequireJS inside WordPress") so simple that to this day, I'm kicking myself for not figuring it out on my own:

> *"...if jquery is already in the page, what you could do is detect for it before doing [a] require() loading and set it up as the 'jquery' module value:*
{% prism javascript %}
if (typeof jQuery === 'function') {
  define('jquery', function () { return jQuery; });
}
//Now require your code:
require(['app'], function (){});
{% endprism %}
> *This assumes jquery was loaded before the require call. If so, then this approach means requirejs will not load another version of jquery."*

Yup...kicking myself for missing the obvious. Had I stuck with WordPress, I would apply `wp_enqueue_script` to jQuery in using the method above, then setup `search.js` like this:

{% prism javascript %}
if (typeof jQuery === 'function') {
  define('jquery', function () { return jQuery; });
}

define(["jquery","tipuesetContent","tipueset","tipue"], function($, tipuesetContent, tipueset, tipue) {

  $("#tipue_search_input").tipuesearch({
    "show": 10,
    "showURL": false,
    "highlightEveryTerm": true
  });

});
{% endprism %}

I tested this inside of WordPress and it worked like a charm, but I had to get jQuery on the page via `wp_enqueue_script`. This meant that jQuery would be placed in a `<script>` tag on my page and be excluded from my final RequireJS build.

This is, generally, not how RequireJS works and I was very stubborn about managing all my site's JavaScript with RequireJS so I could better understand how it works. It was at this point that I went over to Jekyll but if I ever need to use RequireJS and WordPress together, I would do so using the method above.

## RequireJS/AMD, WordPress & The Future?
RequireJS and AMD are gaining in popularity so integrating them into WordPress is worth a discussion. Web searches show some RequireJS implementations inside of WordPress by developers, but there's no indication from the core WP team that AMD functionality will be bundled in a future version.

An interesting discussion has built up around [a feature request ticket to bring AMD JavaScript loading into WordPress](http://core.trac.wordpress.org/ticket/23285 "Read the feature request to bring AMD into WordPress"). Referring primarily to jQuery, the discussion's main point is that the various WordPress plugins don't necessarily use the same versions of the JavaScript library. Some plugins require an older version of jQuery: creating an AMD system that allows plugin developers to load an older version is offered as a solution to the problem.

WordPress somewhat solved this problem with the release of the TwentyThirteen theme. The theme comes bundled with [jQuery Migrate](https://github.com/jquery/jquery-migrate/ "Go to main the jQuery Migrate page"), which detects and loads deprecated jQuery features. Plugin developers in need of jQuery's older features can take advantage of this, after testing things, of course.

At the same time, the core WordPress team encourages plugin authors to update their plugin code when one of their dependencies get updated. jQuery Migrate may be solving a problem, but the core team would prefer it if authors applied updates themselves...WordPress SEO plugin creator [Joost de Valk wrote a great post on this subject](http://yoast.com/why-we-dont-support-old-wordpress-versions/ "Read 'Why we don't support old WordPress versions' by Joost de Valk").

Even if jQuery Migrate didn't solve this problem, I'm of the opinion that WordPress can't do much more than this right now. Integrating RequireJS or another AMD JavaScript solution is nice to have in WP, but not crucial to its growth and survival. And doing so would mean a major code rewrite of how WordPress already handles JavaScript, which is currently fine as is.

Simply put, WordPress is content management system meant to solve customer and business problems. It needs to be demonstrated that AMD/RequireJS can solve such a problems and until that happens, I can't see this functionality landing into WordPress...just my opinion on all this.

## Conclusion
Bringing RequireJS into WordPress is possible, but you may have to make adjustments in some spots to make sure everything works. That's a natural occurrence in web development though, so feel free to review the many links above and go ahead and do so.


text:
// Copyright (c) InfoTeCS JSC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Net;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Infotecs.Cryptography;
using Infotecs.ShellmaContracts.DataContracts;
using NLog;

namespace Infotecs.Shellma
{
    /// <summary>
    ///     Представляет команды работы со службой.
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public sealed class ServiceProvider : IShellmaServiceProvider
    {
        private const string Container = @".\DataStore\UnitTestContainer";
        private const string ContainerPassword = "123123";
        private static readonly Logger log = LogManager.GetCurrentClassLogger();

        /// <summary>
        ///     Подсчет хэша.
        /// </summary>
        /// <param name="data">Данные.</param>
        /// <returns>Хэш.</returns>
        public string ComputeHash(string data)
        {
            log.Debug("ComputeHash: data: {0}", data);
            if (data == null)
            {
                throw new WebFaultException(HttpStatusCode.BadRequest);
            }
            byte[] dataValue = Encoding.UTF8.GetBytes(data);
            return Convert.ToBase64String(KeyContainer.ComputeHash(dataValue));
        }

        /// <summary>
        ///     Конвертирует строку в Hex представление
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ConvertToHex(string data)
        {
            byte[] dataValue = Convert.FromBase64String(data);
            return HexEncoding.ToString(dataValue);
        }

        /// <summary>
        ///     Экспорт открытого ключа.
        /// </summary>
        /// <returns>Открытый ключ.</returns>
        public string ExportPublicKey()
        {
            log.Debug("ExportPublicKey: keyContainerName: {0}", Container);
            return Convert.ToBase64String(KeyContainer.ExportPublicKey(Container));
        }

        /// <summary>
        ///     Подпись хэша.
        /// </summary>
        /// <param name="hash">Хэш.</param>
        /// <returns>Подпись хэша.</returns>
        public string SignHash(string hash)
        {
            if (string.IsNullOrWhiteSpace(hash))
            {
                throw new WebFaultException(HttpStatusCode.BadRequest);
            }

            log.Debug("SignHash: hash: {0}, keyNumber: {1}", hash, KeyNumber.Signature);
            byte[] hashValue = Convert.FromBase64String(hash);
            using (KeyContainer keyContainer = KeyContainer.Open(Container, ContainerPassword))
            {
                byte[] signature = keyContainer.SignHash(hashValue, KeyNumber.Signature);
                return Convert.ToBase64String(signature);
            }
        }

        /// <summary>
        ///     Проверка подписи.
        /// </summary>
        /// <param name="request">Данные.</param>
        /// <returns>True - провека прошла успешно, иначе False.</returns>
        public bool VerifySignature(VerifySignatureRequest request)
        {
            log.Debug("VerifySignature: {0}", request);
            byte[] signatureValue = Convert.FromBase64String(request.Signature);
            byte[] dataValue = Encoding.UTF8.GetBytes(request.Data);
            byte[] publicKeyValue = Convert.FromBase64String(request.PublicKey);
            return KeyContainer.VerifySignature(signatureValue, dataValue, publicKeyValue);
        }

        /// <summary>
        ///     Экспорт сертификата из контейнера.
        /// </summary>
        public string ExportCertificate()
        {
            log.Debug("ExportCertificateData: keyContainerName: {0}", Container);
            return Convert.ToBase64String(KeyContainer.ExportCertificateData(Container));
        }

        /// <summary>
        ///     Проверка подписи.
        /// </summary>
        /// <param name="request">Данные.</param>
        /// <returns>True - провека прошла успешно, иначе False.</returns>
        public bool VerifyCertificate(VerifySignatureCertRequest request)
        {
            log.Debug("VerifySignatureSert: {0}", request);
            byte[] signatureValue = Convert.FromBase64String(request.Signature);
            byte[] dataValue = Encoding.UTF8.GetBytes(request.Data);
            byte[] certificateValue = Convert.FromBase64String(request.Certificate);

            return KeyContainer.VerifyCertificate(signatureValue, dataValue, certificateValue);
        }
    }
}


text:
var deployer = hexo.extend.deployer;

deployer.register('git', require('./git'));
deployer.register('github', require('./github'));
deployer.register('heroku', require('./heroku'));
deployer.register('openshift', require('./openshift'));
deployer.register('rsync', require('./rsync'));


text:
extern "C" {
#include <X11/Xlib.h>
}
#endif

namespace gfx {

std::string GLContextEGL::GetExtensions() {
  const char* extensions = eglQueryString(display_,
                                          EGL_EXTENSIONS);
  if (!extensions)
    return GLContext::GetExtensions();

  return GLContext::GetExtensions() + " " + extensions;
}

GLContextEGL::GLContextEGL(GLShareGroup* share_group)
    : GLContext(share_group),
      context_(NULL),
      display_(NULL),
      config_(NULL) {
}

GLContextEGL::~GLContextEGL() {
  Destroy();
}

bool GLContextEGL::Initialize(
    GLSurface* compatible_surface, GpuPreference gpu_preference) {
  DCHECK(compatible_surface);
  DCHECK(!context_);

  static const EGLint kContextAttributes[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  display_ = compatible_surface->GetDisplay();
  config_ = compatible_surface->GetConfig();

  context_ = eglCreateContext(
      display_,
      config_,
      share_group() ? share_group()->GetHandle() : NULL,
      kContextAttributes);
  if (!context_) {
    LOG(ERROR) << "eglCreateContext failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  return true;
}

void GLContextEGL::Destroy() {
  if (context_) {
    if (!eglDestroyContext(display_, context_)) {
      LOG(ERROR) << "eglDestroyContext failed with error "
                 << GetLastEGLErrorString();
    }

    context_ = NULL;
  }
}

bool GLContextEGL::MakeCurrent(GLSurface* surface) {
  DCHECK(context_);
  if (IsCurrent(surface))
      return true;

  TRACE_EVENT0("gpu", "GLContextEGL::MakeCurrent");

  if (!eglMakeCurrent(display_,
                      surface->GetHandle(),
                      surface->GetHandle(),
                      context_)) {
    DVLOG(1) << "eglMakeCurrent failed with error "
             << GetLastEGLErrorString();
    return false;
  }

  SetCurrent(this, surface);
  if (!InitializeExtensionBindings()) {
    ReleaseCurrent(surface);
    return false;
  }

  if (!surface->OnMakeCurrent(this)) {
    LOG(ERROR) << "Could not make current.";
    return false;
  }

  return true;
}

void GLContextEGL::ReleaseCurrent(GLSurface* surface) {
  if (!IsCurrent(surface))
    return;

  SetCurrent(NULL, NULL);
  eglMakeCurrent(display_,
                 EGL_NO_SURFACE,
                 EGL_NO_SURFACE,
                 EGL_NO_CONTEXT);
}

bool GLContextEGL::IsCurrent(GLSurface* surface) {
  DCHECK(context_);

  bool native_context_is_current = context_ == eglGetCurrentContext();

  // If our context is current then our notion of which GLContext is
  // current must be correct. On the other hand, third-party code
  // using OpenGL might change the current context.
  DCHECK(!native_context_is_current || (GetCurrent() == this));

  if (!native_context_is_current)
    return false;

  if (surface) {
    if (surface->GetHandle() != eglGetCurrentSurface(EGL_DRAW))
      return false;
  }

  return true;
}

void* GLContextEGL::GetHandle() {
  return context_;
}

void GLContextEGL::SetSwapInterval(int interval) {
  DCHECK(IsCurrent(NULL));
  if (!eglSwapInterval(display_, interval)) {
    LOG(ERROR) << "eglSwapInterval failed with error "
               << GetLastEGLErrorString();
  }
}

}  // namespace gfx


text:
TOP=../..

NAME = findlib

OCAMLC = ocamlc
OCAMLOPT = ocamlopt
OCAMLDEP = ocamldep
OCAMLLEX = ocamllex
CAMLP4O =  camlp4 pa_o.cmo pa_op.cmo pr_o.cmo --
#CAMLP4O =  camlp4 pa_o.cmo pa_op.cmo pr_dump.cmo --

OBJECTS        = findlib_config.cmo fl_split.cmo fl_metatoken.cmo fl_meta.cmo \
		 fl_metascanner.cmo fl_topo.cmo fl_package_base.cmo \
	         findlib.cmo
TOBJECTS       = topfind.cmo

XOBJECTS       = $(OBJECTS:.cmo=.cmx)

OCAMLFIND_OBJECTS = ocaml_args.cmo frontend.cmo
OCAMLFIND_XOBJECTS = ocaml_args.cmx frontend.cmx

NUMTOP_OBJECTS = num_top_printers.cmo num_top.cmo

all: ocamlfind$(EXEC_SUFFIX) findlib.cma findlib_top.cma topfind num_top.cma

opt: ocamlfind_opt$(EXEC_SUFFIX) findlib.cmxa topfind

ocamlfind$(EXEC_SUFFIX): findlib.cma $(OCAMLFIND_OBJECTS)
	$(OCAMLC) -custom -o ocamlfind$(EXEC_SUFFIX) findlib.cma unix.cma \
	          $(OCAMLC_FLAGS) $(OCAMLFIND_OBJECTS)

ocamlfind_opt$(EXEC_SUFFIX): findlib.cmxa $(OCAMLFIND_XOBJECTS)
	$(OCAMLOPT) -o ocamlfind_opt$(EXEC_SUFFIX) findlib.cmxa unix.cmxa \
		  $(OCAMLOPT_FLAGS) $(OCAMLFIND_XOBJECTS)

findlib.cma: $(OBJECTS)
	$(OCAMLC) -a -o findlib.cma $(OBJECTS)

findlib_top.cma: $(TOBJECTS)
	$(OCAMLC) -a -o findlib_top.cma $(TOBJECTS)

findlib.cmxa: $(XOBJECTS)
	$(OCAMLOPT) -a -o findlib.cmxa $(XOBJECTS)

findlib_config.ml: findlib_config.mlp $(TOP)/Makefile.config
	USE_CYGPATH="$(USE_CYGPATH)"; \
	export USE_CYGPATH; \
	cat findlib_config.mlp | \
		$(TOP)/tools/patch '@CONFIGFILE@' '$(OCAMLFIND_CONF)' | \
		$(TOP)/tools/patch '@STDLIB@' '$(OCAML_CORE_STDLIB)' | \
		sed -e 's;@AUTOLINK@;$(OCAML_AUTOLINK);g' \
		    -e 's;@SYSTEM@;$(SYSTEM);g' \
		     >findlib_config.ml

topfind: topfind.p
	USE_CYGPATH="$(USE_CYGPATH)"; \
	export USE_CYGPATH; \
	cat topfind.p | \
		$(TOP)/tools/patch '@SITELIB@' '$(OCAML_SITELIB)' \
	    	    >topfind

num_top.cma: $(NUMTOP_OBJECTS)
	$(OCAMLC) -a -o num_top.cma $(NUMTOP_OBJECTS)

clean:
	rm -f *.cmi *.cmo *.cma *.cmx *.a *.o *.cmxa \
	  fl_meta.ml findlib_config.ml findlib.mml topfind \
	  ocamlfind$(EXEC_SUFFIX) ocamlfind_opt$(EXEC_SUFFIX)

install: all
	mkdir -p "$(prefix)$(OCAML_SITELIB)/$(NAME)"
	mkdir -p "$(prefix)$(OCAMLFIND_BIN)"
	test $(INSTALL_TOPFIND) -eq 0 || cp topfind "$(prefix)$(OCAML_CORE_STDLIB)"
	files=`$(TOP)/tools/collect_files $(TOP)/Makefile.config findlib.cmi findlib.mli findlib.cma topfind.cmi topfind.mli fl_package_base.mli fl_package_base.cmi fl_metascanner.mli fl_metascanner.cmi fl_metatoken.cmi findlib_top.cma findlib.cmxa findlib.a META` && \
	cp $$files "$(prefix)$(OCAML_SITELIB)/$(NAME)"
	f="ocamlfind$(EXEC_SUFFIX)"; { test -f ocamlfind_opt$(EXEC_SUFFIX) && f="ocamlfind_opt$(EXEC_SUFFIX)"; }; \
	cp $$f "$(prefix)$(OCAMLFIND_BIN)/ocamlfind$(EXEC_SUFFIX)"

install-num-top:
	mkdir -p "$(prefix)$(OCAML_SITELIB)/num-top"
	cp num_top.cma num_top.cmi num_top_printers.cmi \
		"$(prefix)$(OCAML_SITELIB)/num-top"

# Note: uninstall-num-top is part of the removal of the META files.

uninstall:
	rm -f $(prefix)$(OCAML_CORE_STDLIB)/findlib
	rm -rf $(prefix)$(OCAML_SITELIB)/$(NAME)
	rm -f $(prefix)$(OCAMLFIND_BIN)/ocamlfind$(EXEC_SUFFIX)

depend: *.ml *.mli fl_meta.ml fl_metascanner.ml
	$(OCAMLDEP) *.ml *.mli >depend

# Some 'make' implementations require that .SUFFIXES must occur before
# the first suffix rule. (E.g. AIX)
.SUFFIXES: .mll .cmo .cmi .cmx .ml .mli .mml .src

.mml.cmo:
	$(OCAMLC) -g -vmthread -c -impl $<

.mml.cmx:
	$(OCAMLOPT) -thread -c -impl $<

.ml.cmx:
	$(OCAMLOPT) -c $<

.ml.cmo:
	$(OCAMLC) -g -c $<

.mli.cmi:
	$(OCAMLC) -c $<

.src.ml:
	$(CAMLP4O) -impl $< -o $@

# Solaris make does not like the suffix rule .mll.ml,
# so I replaced it by its single application:
fl_meta.ml: fl_meta.mll
	$(OCAMLLEX) fl_meta.mll

# Don't remove fl_metascanner.ml:
.PRECIOUS: fl_metascanner.ml

include $(TOP)/Makefile.config
include depend


text:
layout: post
status: publish
published: true
title: Cambiar el valor de un input desde un modal con y sin jQuery
author:
  display_name: markitos
  login: markitos
  email: markitosco@gmail.com
  url: ''
author_login: markitos
author_email: markitosco@gmail.com
wordpress_id: 2263
wordpress_url: http://www.becodemyfriend.com/?p=2263
date: '2011-11-02 15:12:15 +0000'
date_gmt: '2011-11-02 14:12:15 +0000'
categories:
- Programación
tags:
- Programación
- Javascript
---

Pongamos por caso que tenemos un formulario que abre un modal de selección y, desde ese modal (iframe), queremos cambiar con jQuery el valor de un input de la ventana padre…

Muy fácil:

$('#id_del_input', window.parent.document).val('valor');

Sin jQuery también podemos hacerlo de la siguiente manera:

window.parent.document.getElementById('id_del_input').value='valor';


text:
exports.up = knex => knex.schema.createTable('users', table => {
  table.bigincrements('id').primary();
  table.string('email').unique().notNullable();
  table.string('password').notNullable();
  table.string('name');
  table.string('created_at').notNullable();
  table.string('updated_at').notNullable();
});

exports.down = knex => {
  return knex.schema.dropTable('users');
};


text:
package org.kie.workbench.common.stunner.client.widgets.presenters.session.impl;

import javax.enterprise.event.Event;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.client.widgets.event.SessionDiagramOpenedEvent;
import org.kie.workbench.common.stunner.client.widgets.notification.NotificationsObserver;
import org.kie.workbench.common.stunner.client.widgets.palette.BS3PaletteWidget;
import org.kie.workbench.common.stunner.client.widgets.palette.factory.BS3PaletteFactory;
import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionDiagramPreview;
import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionPresenter;
import org.kie.workbench.common.stunner.client.widgets.toolbar.impl.EditorToolbar;
import org.kie.workbench.common.stunner.client.widgets.toolbar.impl.EditorToolbarFactory;
import org.kie.workbench.common.stunner.client.widgets.toolbar.impl.ViewerToolbarFactory;
import org.kie.workbench.common.stunner.client.widgets.views.WidgetWrapperView;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandManager;
import org.kie.workbench.common.stunner.core.client.event.screen.ScreenMaximizedEvent;
import org.kie.workbench.common.stunner.core.client.event.screen.ScreenMinimizedEvent;
import org.kie.workbench.common.stunner.core.client.event.screen.ScreenResizeEventObserver;
import org.kie.workbench.common.stunner.core.client.session.impl.AbstractClientFullSession;
import org.kie.workbench.common.stunner.core.client.session.impl.AbstractClientSession;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SessionEditorPresenterTest {

    private SessionEditorPresenter<AbstractClientFullSession, AbstractCanvasHandler> sessionEditorPresenter;

    private ScreenResizeEventObserver screenResizeEventObserver;

    @Mock
    private SessionManager sessionManager;

    @Mock
    private CanvasCommandManager<AbstractCanvasHandler> commandManagerInstances;

    @Mock
    private ViewerToolbarFactory viewerToolbarFactoryInstances;

    @Mock
    private EditorToolbarFactory editorToolbarFactoryInstances;

    @Mock
    private SessionDiagramPreview<AbstractClientSession> sessionPreviewInstances;

    @Mock
    private WidgetWrapperView diagramViewerViewInstances;

    @Mock
    private SessionPresenter.View viewInstances;

    @Mock
    private NotificationsObserver notificationsObserverInstances;

    @Mock
    private BS3PaletteFactory paletteWidgetFactory;

    @Mock
    private Event<SessionDiagramOpenedEvent> sessionDiagramOpenedEventInstances;

    @Mock
    private BS3PaletteWidget paletteWidget;

    @Mock
    private AbstractClientFullSession clientFullSession;

    @Mock
    private EditorToolbar toolbar;

    @Mock
    private AbstractCanvasHandler canvasHandler;

    @Mock
    private Diagram diagram;

    @Captor
    private ArgumentCaptor<ScreenMaximizedEvent> screenMaximizedEventArgumentCaptor;

    @Captor
    private ArgumentCaptor<ScreenMinimizedEvent> screenMinimizedEventArgumentCaptor;

    @Before
    public void init() throws Exception {

        screenResizeEventObserver = new ScreenResizeEventObserver();

        sessionEditorPresenter = new SessionEditorPresenter<>(sessionManager,
                                                              commandManagerInstances,
                                                              sessionDiagramOpenedEventInstances,
                                                              editorToolbarFactoryInstances,
                                                              paletteWidgetFactory,
                                                              diagramViewerViewInstances,
                                                              notificationsObserverInstances,
                                                              viewInstances,
                                                              screenResizeEventObserver);

        when(paletteWidgetFactory.newPalette(anyString())).thenReturn(paletteWidget);
        when(editorToolbarFactoryInstances.build(clientFullSession)).thenReturn(toolbar);

        when(clientFullSession.getCanvasHandler()).thenReturn(canvasHandler);

        when(canvasHandler.getDiagram()).thenReturn(diagram);

        when(diagram.getMetadata()).thenReturn(Mockito.mock(Metadata.class));

        when(paletteWidgetFactory.newPalette(anyString(),
                                             any())).thenReturn(paletteWidget);

        when(viewInstances.setPaletteWidget(any())).thenReturn(viewInstances);

        sessionEditorPresenter.onSessionOpened(clientFullSession);
    }

    @Test
    public void screenResizeEventTest() throws Exception {
        screenResizeEventObserver.onEventReceived(new ScreenMaximizedEvent(true));
        screenResizeEventObserver.onEventReceived(new ScreenMaximizedEvent(false));
        screenResizeEventObserver.onEventReceived(new ScreenMinimizedEvent(true));
        screenResizeEventObserver.onEventReceived(new ScreenMinimizedEvent(false));

        InOrder inOrder = inOrder(paletteWidget);
        inOrder.verify(paletteWidget, times(2)).onScreenMaximized(screenMaximizedEventArgumentCaptor.capture());
        inOrder.verify(paletteWidget, times(2)).onScreenMinimized(screenMinimizedEventArgumentCaptor.capture());

        assertTrue(screenMaximizedEventArgumentCaptor.getAllValues().get(0).isDiagramScreen());
        assertFalse(screenMaximizedEventArgumentCaptor.getAllValues().get(1).isDiagramScreen());
        assertTrue(screenMinimizedEventArgumentCaptor.getAllValues().get(0).isDiagramScreen());
        assertFalse(screenMinimizedEventArgumentCaptor.getAllValues().get(1).isDiagramScreen());
    }
}


text:
package org.jetbrains.plugins.groovy.codeInspection.secondUnsafeCall;

import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.annotator.inspections.SecondUnsafeCallQuickFix;
import org.jetbrains.plugins.groovy.codeInspection.GroovyLocalInspectionTool;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;

public class SecondUnsafeCallInspection extends GroovyLocalInspectionTool {

  @Override
  public @NotNull GroovyElementVisitor buildGroovyVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    return new GroovyElementVisitor() {
      @Override
      public void visitReferenceExpression(@NotNull GrReferenceExpression refExpression) {
        checkForSecondUnsafeCall(refExpression, holder);
      }
    };
  }

  private static void checkForSecondUnsafeCall(GrExpression expression, ProblemsHolder holder) {
    checkForSecondUnsafeCall(expression, holder, null);
  }

  private static void checkForSecondUnsafeCall(GrExpression expression, ProblemsHolder holder, @Nullable PsiElement highlightElement) {
    if (highlightElement == null) highlightElement = expression;

    final GrReferenceExpression referenceExpression = (GrReferenceExpression)expression;

    if (GroovyTokenTypes.mDOT.equals(referenceExpression.getDotTokenType())) {
      //        a?.b or a?.b()
      final GrExpression qualifier = referenceExpression.getQualifierExpression();
      //        a?.b()
      if (qualifier instanceof GrMethodCallExpression) {
        final GrExpression expression1 = ((GrMethodCallExpression)qualifier).getInvokedExpression();
        //        a?.b
        if (!(expression1 instanceof GrReferenceExpression)) return;

        if (GroovyTokenTypes.mOPTIONAL_DOT.equals(((GrReferenceExpression)expression1).getDotTokenType())) {
          holder.registerProblem(highlightElement, GroovyBundle.message("call.can.throw.npe"), new SecondUnsafeCallQuickFix());
        }
      }
      else
        //        a?.b
        if (qualifier instanceof GrReferenceExpression) {
          if (GroovyTokenTypes.mOPTIONAL_DOT.equals(((GrReferenceExpression)qualifier).getDotTokenType())) {
            holder.registerProblem(highlightElement, GroovyBundle.message("call.can.throw.npe"), new SecondUnsafeCallQuickFix());
          }
        }
    }
  }
}


text:
package game

import (
	"fmt"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

// Roll a set of d s-sided die.
func DieRoll(d, s int) int {
	total := 0
	for i := 0; i < d; i++ {
		total += 1 + intsource(s)
	}
	return total
}

// Thin wrapper over math/rand so that we can stub out in tests. This is
// basically "what do you want me to use as Intn(n)".
type IntSource func(int) int

// The current source that random functions from here will use.
var intsource IntSource = rand.Intn

// The backup, if the "normal" source has been swapped out.
var oldintsource IntSource = nil

// "Fix" the random generator to return ints from the given sequence. Also
// returns the closure that substitutes intsource, if you want to chain it in
// subsequent fakes.
func FixRandomSource(ints []int) func(int) int {
	oldintsource = intsource
	n := 0
	intsource = func(_ int) int {
		x := ints[n]
		n++
		return x
	}
	return intsource
}

// An intsource that subtracts 1 to each element in the list. This makes it
// compatible with rigging dierolls directly, since DieRoll has to add one to
// each int to represent a roll from 1 to n (instead of 0 to n-1).
func FixRandomDie(ints []int) func(int) int {
	f := FixRandomSource(ints)
	intsource = func(i int) int {
		return f(i) - 1
	}
	return intsource
}

// Restore the random generator the way it was.
func RestoreRandom() {
	intsource = oldintsource
	oldintsource = nil
}

type Dice struct {
	Dice  int
	Sides int
}

var ZeroDice = Dice{}

func NewDice(dice, sides int) Dice {
	return Dice{Dice: dice, Sides: sides}
}

func (d Dice) Add(dice, sides int) Dice {
	return NewDice(d.Dice+dice, d.Sides+sides)
}

func (d Dice) Roll() int {
	return DieRoll(d.Dice, d.Sides)
}

func (d Dice) String() string {
	return fmt.Sprintf("%dd%d", d.Dice, d.Sides)
}

func RandInt(low int, high int) int {
	return low + intsource(high-low)
}

func OneIn(n int) bool {
	return intsource(n) == 0
}

func Coinflip() bool {
	return OneIn(2)
}

type Weighter interface {
	Weight() int
}

// Selects 1 item from a weighted list of choices. In the weighted list {a: 1,
// b: 2, c: 1}, we'd expect to see a selected 25% of the time, b selected 50%
// of the time, and c selected 25% of the time.
func WChoose(choices []Weighter) (pos int, chosen Weighter) {
	if len(choices) == 0 {
		return -1, nil
	}

	// This is not necessary -- the loop below would handle this case. However,
	// we use this function REALLY often in fighting-related tests where we
	// already have to stub out a bunch of dierolls, and basically all of those
	// tests use a single attack. To avoid having to put a leading '0' in every
	// fake rolls list, we handle this case without consuming a random number.
	if len(choices) == 1 {
		return 0, choices[0]
	}

	// Compute total weight of all items in choices.
	tw := 0
	for _, item := range choices {
		tw += item.Weight()
	}

	// Select a random number in [0,tw). Now, continually add up weights. When
	// we finally get a weight > r, select that item.
	r, cw := RandInt(0, tw), 0
	for i, item := range choices {
		cw += item.Weight()
		if r < cw {
			return i, item
		}
	}

	// This should never happen.
	panic(fmt.Sprintf("Could not WChoose from %+v", choices))
}


text:
import sbt._
import Keys._
import PlayProject._

object ApplicationBuild extends Build {

    val appName         = "sleeper"
    val appVersion      = "1.0-SNAPSHOT"

    val appDependencies = Seq(
      // Add your project dependencies here,
    )

    val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
      // Add your own project settings here
    )

}


text:
package org.jboss.pnc.messaging;

import org.jboss.pnc.common.json.moduleconfig.SystemConfig;

import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;

/**
 * @author Matej Lazar
 */
@Dependent
public class SysConfigProducer {

    @Produces
    public SystemConfig createSystemConfig() {
        // SystemConfig systemConfig = Mockito.mock(SystemConfig.class);
        // Mockito.when(systemConfig.getMessagingInternalQueueSize()).thenReturn(2);
        // return systemConfig;

        return new SystemConfig(null, null, null, null, null, null, null, "10", null, null, null, "", "2");
    }
}


text:
function Tag(impl, conf, innerHTML) {

  var self = riot.observable(this),
      opts = inherit(conf.opts) || {},
      dom = mkdom(impl.tmpl),
      parent = conf.parent,
      isLoop = conf.isLoop,
      item = conf.item,
      expressions = [],
      childTags = [],
      root = conf.root,
      fn = impl.fn,
      tagName = root.tagName.toLowerCase(),
      attr = {},
      propsInSyncWithParent = [],
      loopDom,
      TAG_ATTRIBUTES = /([\w\-]+)\s?=\s?['"]([^'"]+)["']/gim

  if (fn && root._tag) {
    root._tag.unmount(true)
  }

  // not yet mounted
  this.isMounted = false

  if (impl.attrs) {
    var attrs = impl.attrs.match(TAG_ATTRIBUTES)

    each(attrs, function(a) {
      var kv = a.split(/\s?=\s?/)
      root.setAttribute(kv[0], kv[1].replace(/['"]/g, ''))
    })

  }

  // keep a reference to the tag just created
  // so we will be able to mount this tag multiple times
  root._tag = this

  // create a unique id to this tag
  // it could be handy to use it also to improve the virtual dom rendering speed
  this._id = fastAbs(~~(new Date().getTime() * Math.random()))

  extend(this, { parent: parent, root: root, opts: opts, tags: {} }, item)

  // grab attributes
  each(root.attributes, function(el) {
    var val = el.value
    // remember attributes with expressions only
    if (brackets(/\{.*\}/).test(val)) attr[el.name] = val
  })

  if (dom.innerHTML && !/select|select|optgroup|tbody|tr/.test(tagName))
    // replace all the yield tags with the tag inner html
    dom.innerHTML = replaceYield(dom.innerHTML, innerHTML)

  // options
  function updateOpts() {
    // update opts from current DOM attributes
    each(root.attributes, function(el) {
      opts[el.name] = tmpl(el.value, parent || self)
    })
    // recover those with expressions
    each(Object.keys(attr), function(name) {
      opts[name] = tmpl(attr[name], parent || self)
    })
  }

  function normalizeData(data) {
    for (var key in item) {
      if (typeof self[key] != 'undefined')
        self[key] = data[key]
    }
  }

  function inheritFromParent () {
    if (!self.parent || !isLoop) return
    each(Object.keys(self.parent), function(k) {
      // some properties must be always in sync with the parent tag
      var mustSync = ~propsInSyncWithParent.indexOf(k)
      if (typeof self[k] == 'undefined' || mustSync) {
        // track the property to keep in sync
        // so we can keep it updated
        if (!mustSync) propsInSyncWithParent.push(k)
        self[k] = self.parent[k]
      }
    })
  }

  this.update = function(data) {
    // inherit properties from the parent
    inheritFromParent()
    // normalize the tag properties in case an item object was initially passed
    if (item && JSON.stringify(item) != JSON.stringify(data)) {
      normalizeData(data)
      item = data
    }
    extend(self, data)
    updateOpts()
    self.trigger('update', data)
    update(expressions, self, data)
    self.trigger('updated')
  }

  this.mixin = function() {
    each(arguments, function(mix) {
      mix = typeof mix == 'string' ? riot.mixin(mix) : mix
      each(Object.keys(mix), function(key) {
        // bind methods to self
        if (key != 'init')
          self[key] = typeof mix[key] == 'function' ? mix[key].bind(self) : mix[key]
      })
      // init method will be called automatically
      if (mix.init) mix.init.bind(self)()
    })
  }

  this.mount = function() {

    updateOpts()

    // initialiation
    fn && fn.call(self, opts)

    toggle(true)

    // parse layout after init. fn may calculate args for nested custom tags
    parseExpressions(dom, self, expressions)

    if (!self.parent || isLoop) self.update(item)

    // internal use only, fixes #403
    self.trigger('premount')

    if (isLoop) {
      // update the root attribute for the looped elements
      self.root = root = loopDom = dom.firstChild
    } else {
      while (dom.firstChild) root.appendChild(dom.firstChild)
      if (root.stub) self.root = root = parent.root
    }
    // if it's not a child tag we can trigger its mount event
    if (!self.parent || self.parent.isMounted) {
      self.isMounted = true
      self.trigger('mount')
    }
    // otherwise we need to wait that the parent event gets triggered
    else self.parent.one('mount', function() {
      // avoid to trigger the `mount` event for the tags
      // not visible included in an if statement
      if (!isInStub(self.root)) {
        self.parent.isMounted = self.isMounted = true
        self.trigger('mount')
      }
    })
  }

  this.unmount = function(keepRootTag) {
    var el = loopDom || root,
        p = el.parentNode

    if (p) {

      if (parent)
        // remove this tag from the parent tags object
        // if there are multiple nested tags with same name..
        // remove this element form the array
        if (isArray(parent.tags[tagName]))
          each(parent.tags[tagName], function(tag, i) {
            if (tag._id == self._id)
              parent.tags[tagName].splice(i, 1)
          })
        else
          // otherwise just delete the tag instance
          parent.tags[tagName] = undefined
      else
        while (el.firstChild) el.removeChild(el.firstChild)

      if (!keepRootTag)
        p.removeChild(el)

    }

    self.trigger('unmount')
    toggle()
    self.off('*')
    // somehow ie8 does not like `delete root._tag`
    root._tag = null

  }

  function toggle(isMount) {

    // mount/unmount children
    each(childTags, function(child) { child[isMount ? 'mount' : 'unmount']() })

    // listen/unlisten parent (events flow one way from parent to children)
    if (parent) {
      var evt = isMount ? 'on' : 'off'

      // the loop tags will be always in sync with the parent automatically
      if (isLoop)
        parent[evt]('unmount', self.unmount)
      else
        parent[evt]('update', self.update)[evt]('unmount', self.unmount)
    }
  }

  // named elements available for fn
  parseNamedElements(dom, this, childTags)

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<clientConfig version="1.1">
  <emailProvider id="upcmail.nl">
    <domain>upcmail.nl</domain>
    <domain>chello.nl</domain>
    <displayName>UPC Nederland</displayName>
    <displayShortName>UPC</displayShortName>
    <incomingServer type="pop3">
      <hostname>pop3.upcmail.nl</hostname>
      <port>110</port>
      <socketType>plain</socketType>
      <username>%EMAILADDRESS%</username>
      <authentication>password-cleartext</authentication>
    </incomingServer>
    <outgoingServer type="smtp">
      <hostname>smtp.upcmail.nl</hostname>
      <port>25</port>
      <socketType>plain</socketType>
      <username>%EMAILADDRESS%</username>
      <authentication>client-IP-address</authentication>
    </outgoingServer>
  </emailProvider>
</clientConfig>


text:
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __vueComponentTransformJSXProps from '../runtime-helpers/vue-component-transform-jsx-props.js';
import __vueComponentDispatchEvent from '../runtime-helpers/vue-component-dispatch-event.js';
import __vueComponentProps from '../runtime-helpers/vue-component-props.js';
export default {
  name: 'f7-list-button',
  props: Object.assign({
    id: [String, Number],
    title: [String, Number],
    text: [String, Number],
    tabLink: [Boolean, String],
    tabLinkActive: Boolean,
    link: [Boolean, String],
    href: [Boolean, String],
    target: String,
    tooltip: String,
    tooltipTrigger: String
  }, Mixins.colorProps, {}, Mixins.linkRouterProps, {}, Mixins.linkActionsProps),

  render() {
    const _h = this.$createElement;
    const self = this;
    const props = this.props;
    const {
      className,
      id,
      style,
      title,
      text
    } = props;
    return _h('li', {
      style: style,
      class: className,
      attrs: {
        id: id
      }
    }, [_h('a', __vueComponentTransformJSXProps(Object.assign({
      class: self.classes
    }, self.attrs, {
      ref: 'linkEl'
    })), [this.$slots['default'] || [title || text]])]);
  },

  computed: {
    attrs() {
      const self = this;
      const props = self.props;
      const {
        link,
        href,
        target,
        tabLink
      } = props;
      return Utils.extend({
        href: typeof link === 'boolean' && typeof href === 'boolean' ? '#' : link || href,
        target,
        'data-tab': Utils.isStringProp(tabLink) && tabLink
      }, Mixins.linkRouterAttrs(props), Mixins.linkActionsAttrs(props));
    },

    classes() {
      const self = this;
      const props = self.props;
      const {
        tabLink,
        tabLinkActive
      } = props;
      return Utils.classNames({
        'list-button': true,
        'tab-link': tabLink || tabLink === '',
        'tab-link-active': tabLinkActive
      }, Mixins.colorClasses(props), Mixins.linkRouterClasses(props), Mixins.linkActionsClasses(props));
    },

    props() {
      return __vueComponentProps(this);
    }

  },
  watch: {
    'props.tooltip': function watchTooltip(newText) {
      const self = this;

      if (!newText && self.f7Tooltip) {
        self.f7Tooltip.destroy();
        self.f7Tooltip = null;
        delete self.f7Tooltip;
        return;
      }

      if (newText && !self.f7Tooltip && self.$f7) {
        self.f7Tooltip = self.$f7.tooltip.create({
          targetEl: self.$refs.el,
          text: newText,
          trigger: self.props.tooltipTrigger
        });
        return;
      }

      if (!newText || !self.f7Tooltip) return;
      self.f7Tooltip.setText(newText);
    }
  },

  created() {
    Utils.bindMethods(this, ['onClick']);
  },

  mounted() {
    const self = this;
    const linkEl = self.$refs.linkEl;
    const {
      routeProps,
      tooltip,
      tooltipTrigger
    } = self.props;

    if (routeProps) {
      linkEl.f7RouteProps = routeProps;
    }

    linkEl.addEventListener('click', self.onClick);
    self.$f7ready(f7 => {
      if (tooltip) {
        self.f7Tooltip = f7.tooltip.create({
          targetEl: linkEl,
          text: tooltip,
          trigger: tooltipTrigger
        });
      }
    });
  },

  updated() {
    const self = this;
    const linkEl = self.$refs.linkEl;
    const {
      routeProps
    } = self.props;

    if (routeProps) {
      linkEl.f7RouteProps = routeProps;
    }
  },

  beforeDestroy() {
    const self = this;
    const linkEl = self.$refs.linkEl;
    linkEl.removeEventListener('click', this.onClick);
    delete linkEl.f7RouteProps;

    if (self.f7Tooltip && self.f7Tooltip.destroy) {
      self.f7Tooltip.destroy();
      self.f7Tooltip = null;
      delete self.f7Tooltip;
    }
  },

  methods: {
    onClick(event) {
      this.dispatchEvent('click', event);
    },

    dispatchEvent(events, ...args) {
      __vueComponentDispatchEvent(this, events, ...args);
    }

  }
};


text:
+++
Description = ""
date = "2016-09-22T13:26:41+01:00"
title = "End-to-end video decoding tutorial"
+++

## Introduction
The purpose of this tutorial is to give a simple list of steps to decode a single video on a Nexys4 DDR FPGA using lowRISC.

The extension describes how to use the accelerators.

## Step 1: The Generic lowRISC setup

Start by cloning our version of the lowRISC repository and running the typical set up commands:

```
git clone https://github.com/nbdd0121/lowrisc-chip.git
cd lowrisc-chip
git checkout vga
./setup_env.sh
git submodule update --init --recursive....
```

This tutorial relies heavily on two tools (Vivado and the RISC-V cross compiler) and requires a host of other packages. Wei Song has provided a [tutorial](https://www.lowrisc.org/docs/debug-v0.3/environment/) for setting up the environment. Install the packages on the linked page, then go to the next page ('[Generic lowRISC setup](https://www.lowrisc.org/docs/debug-v0.3/lowriscsetup/)') and follow the tutorials for [Vivado](https://www.lowrisc.org/docs/untether-v0.2/xilinx/) and the [cross-compiler](https://www.lowrisc.org/docs/untether-v0.2/riscv_compile/).

## Step 2: Building the MPEG-2 Codec
We're using a modified version of a reference MPEG-2 implementation. Start by pulling that and cross compiling it for RISC-V.

```bash
git clone https://github.com/ndavison21/lowrisc-mpeg2decode.git
cd lowrisc-mpeg2decode
make mpeg2decode-riscv
```

This results in an executable, located in src/mpeg2decode, called mpeg2decode. We will be using this later on.
The Makefile uses the gcc RISC-V cross compiler, if you get an error message such as:

```bash
riscv64-unknown-linux-gnu-gcc: Command not found
```

ensure that:

* The RISC-V cross compiler has been built
* The RISCV environment variable has been set and points to $TOP/tools/riscv/debug-v0.3
* The cross compiler has been added to the PATH environment variable: if in doubt, run:
```
export PATH=$PATH:$RISCV/bin
```

## Step 3: Setting up the Vivado project

The next steps use Vivado, which requires a few more environment variables. Customise the instructions below for your setup, and then run it.

```bash
export FPGA_BOARD=nexys4_ddr
export XILINXD_LICENSE_FILE=PATH/TO/LICENSE/FILE
source [path to vivado]/xilinx/Vivado/2015.4/settings64.sh
export XILINX_VIVADO
```

Switch to the fpga directory in the lowRISC repository to set up the Vivado project and generate the boot program:

```bash
cd $TOP/fpga/board/nexys4ddr
make project
make boot
```
NOTE: The first time you run `make boot`, it will take a while time to run, and will use a large amount of memory. It may be necessary to close other programs while this is running.

## Step 4: Building the boot image

The decoder runs on Linux, so it's necessary to download and compile the Linux kernel (we're using version 4.6.2) as well as BusyBox.

First move the cross compiled MPEG-2 decoder built in Step 2 to the directory $TOP/riscv-tools/ramfs-merge, along with the .mpg file you wish to play on the FPGA. The video MUST be less than 10 MB in size.
The decoder relies on several library files, for ease of use these are already present in the ramfs-merge directory in this branch.

Once this is done, run the below script.

```bash
cd $TOP/riscv-tools
curl https://www.kernel.org/pub/linux/kernel/v4.x/linux-4.6.2.tar.xz \
  | tar -xJ
cd linux-4.6.2
git init
git remote add origin https://github.com/lowrisc/riscv-linux.git
git fetch
git checkout -f -t origin/debug-v0.3
cd $TOP/riscv-tools
curl -L http://busybox.net/downloads/busybox-1.21.1.tar.bz2 | tar -xj
cd busybox-1.21.1
cp $TOP/riscv-tools/busybox_config .config
make -j$(nproc)
cd $TOP/riscv-tools
./make_root.sh
```

`make_root.sh` builds both BusyBox and Linux. Due to an issue with Vivado, the build of Linux may fail with an error message that looks something like this:

```bash
awk: symbol lookup error: awk: undefined symbol: mpfr_z_sub
```

This occurs because of a conflict between Vivado and awk, detailed [here](http://www.xilinx.com/support/answers/66998.html). Since Vivado is not needed for these steps, an easy solution is starting a fresh terminal and only repeating the following steps before reattempting the above script:
* ./setup_env.sh, this script is located in the top level directory
* Setting up RISCV and PATH as discussed at the end of Step 2.

Once this has successfully completed, a file called `boot.bin` appears in the current directory ($TOP/riscv-tools). This must be copied onto the sd card, which is then to be placed into the FPGA.

## Step 5: Programming the FPGA

Now, it's finally time to program the FPGA. First, a hardware server needs to be started, TODO (source xilinx\_env, run hw\_server)

You can interact with the FPGA using microcom, as shown below:
```bash
microcom -p /dev/ttyUSB1 -s 115200
```

Switch to the nexys4_ddr directory, plug in the FPGA and run `make program-updated`.
```
cd $TOP/fpga/board/nexys4ddr
make program-updated
```

The following should appear, if nothing appears, press the `CPU Reset` button on the FPGA. :
```
Load boot.bin into memory
```

This will take a while as the boot program is copied to memory and linux boots up. The end of the process is not obvious - it's finished when the following output appears:

```
[    0.410000] mmcblk0: p1
```

Now, a somewhat barebones terminal is available (familiar shortcuts such as tab-completion and usage of the arrow keys aren't present). Connect the FPGA to a VGA monitor and run:

```bash
./mpeg2decode -f -b video.mpg -o6
```

Where video.mpg is the video file loaded earlier. The video should now play on the monitor from the FPGA.

## Extension: Using accelerators

It is possible to use the accelerators we have created with a slight
alteration to **Step 1** described above. In order to include the accelerators
in the synthesis, replace `git checkout vga` with `git checkout acc`, and the
run the other instructions as before.

When it comes to running the codec, a final option specifying the accelerator to use is needed. To run all the accelerators the command is
```bash
./mpeg2decode -f -b video.mpg -o6 -a15
```
To run individual accelerators, replace `15` with the following values

| Accelerator     | Binary | Decimal |
|-----------------|--------|----------|
| Y'UV 422 to 444 | 0001   | 1        |
| Y'UV 444 to RGB | 0010   | 2        |
| RGB 32 to 16    | 0100   | 4        |
| IDCT            | 1000   | 8        |
| ALL             | 1111   | 15       |

(each bit indicates the presence or absence of a specific accelerator, as indicated above)


text:
import dotEnv from 'dotenv';
import env from '../helpers/env';

// .env config implementation
dotEnv.config();

env.verifyEnvironmentVariables();


text:
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Database\InsertTest.
 */

namespace Drupal\system\Tests\Database;

/**
 * Tests the insert builder.
 *
 * @group Database
 */
class InsertTest extends DatabaseTestBase {

  /**
   * Tests very basic insert functionality.
   */
  function testSimpleInsert() {
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();

    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Yoko',
      'age' => '29',
    ));
    $query->execute();

    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
    $this->assertIdentical($num_records_before + 1, (int) $num_records_after, 'Record inserts correctly.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
    $this->assertIdentical($saved_age, '29', 'Can retrieve after inserting.');
  }

  /**
   * Tests that we can insert multiple records in one query object.
   */
  function testMultiInsert() {
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();

    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));

    // We should be able to specify values in any order if named.
    $query->values(array(
      'age' => '31',
      'name' => 'Curly',
    ));

    // We should be able to say "use the field order".
    // This is not the recommended mechanism for most cases, but it should work.
    $query->values(array('Moe', '32'));
    $query->execute();

    $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
    $this->assertIdentical($num_records_before + 3, $num_records_after, 'Record inserts correctly.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  }

  /**
   * Tests that an insert object can be reused with new data after it executes.
   */
  function testRepeatedInsert() {
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();

    $query = db_insert('test');

    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));
    $query->execute();  // This should run the insert, but leave the fields intact.

    // We should be able to specify values in any order if named.
    $query->values(array(
      'age' => '31',
      'name' => 'Curly',
    ));
    $query->execute();

    // We should be able to say "use the field order".
    $query->values(array('Moe', '32'));
    $query->execute();

    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
    $this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, 'Record inserts correctly.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  }

  /**
   * Tests that we can specify fields without values and specify values later.
   */
  function testInsertFieldOnlyDefinition() {
    // This is useful for importers, when we want to create a query and define
    // its fields once, then loop over a multi-insert execution.
    db_insert('test')
      ->fields(array('name', 'age'))
      ->values(array('Larry', '30'))
      ->values(array('Curly', '31'))
      ->values(array('Moe', '32'))
      ->execute();
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  }

  /**
   * Tests that inserts return the proper auto-increment ID.
   */
  function testInsertLastInsertID() {
    $id = db_insert('test')
      ->fields(array(
        'name' => 'Larry',
        'age' => '30',
      ))
      ->execute();

    $this->assertIdentical($id, '5', 'Auto-increment ID returned successfully.');
  }

  /**
   * Tests that the INSERT INTO ... SELECT (fields) ... syntax works.
   */
  function testInsertSelectFields() {
    $query = db_select('test_people', 'tp');
    // The query builder will always append expressions after fields.
    // Add the expression first to test that the insert fields are correctly
    // re-ordered.
    $query->addExpression('tp.age', 'age');
    $query
      ->fields('tp', array('name','job'))
      ->condition('tp.name', 'Meredith');

    // The resulting query should be equivalent to:
    // INSERT INTO test (age, name, job)
    // SELECT tp.age AS age, tp.name AS name, tp.job AS job
    // FROM test_people tp
    // WHERE tp.name = 'Meredith'
    db_insert('test')
      ->from($query)
      ->execute();

    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
    $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  }

  /**
   * Tests that the INSERT INTO ... SELECT * ... syntax works.
   */
  function testInsertSelectAll() {
    $query = db_select('test_people', 'tp')
      ->fields('tp')
      ->condition('tp.name', 'Meredith');

    // The resulting query should be equivalent to:
    // INSERT INTO test_people_copy
    // SELECT *
    // FROM test_people tp
    // WHERE tp.name = 'Meredith'
    db_insert('test_people_copy')
      ->from($query)
      ->execute();

    $saved_age = db_query('SELECT age FROM {test_people_copy} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
    $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  }

  /**
   * Tests that we can INSERT INTO a special named column.
   */
  function testSpecialColumnInsert() {
    $id = db_insert('test_special_columns')
      ->fields(array(
        'id' => 2,
        'offset' => 'Offset value 2',
      ))
      ->execute();
    $saved_value = db_query('SELECT "offset" FROM {test_special_columns} WHERE id = :id', array(':id' => 2))->fetchField();
    $this->assertIdentical($saved_value, 'Offset value 2', 'Can retrieve special column name value after inserting.');
  }
}


text:
package org.kaazing.gateway.transport.wsn.specification.ws.connector;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.CountDownLatch;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.MethodExecutionTrace;

public class DataFramingIT {
    private final WsnConnectorRule connector = new WsnConnectorRule();
    private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/ws/data");
    private final TestRule timeoutRule = new DisableOnDebug(Timeout.builder().withTimeout(10, SECONDS)
                .withLookingForStuckThread(true).build());
    private final TestRule trace = new MethodExecutionTrace();

    @Rule
    public TestRule chain = RuleChain.outerRule(trace).around(timeoutRule).around(connector).around(k3po);

    private Mockery context;

    @Before
    public void initialize() {
        context = new Mockery();
        context.setThreadingPolicy(new Synchroniser());
    }

    @Test
    @Specification({
        "server.send.opcode.0x03/handshake.response.and.frame" })
    public void shouldFailWebSocketConnectionWhenServerSendOpcode3Frame() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);
        final CountDownLatch latch = new CountDownLatch(1);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                oneOf(handler).sessionClosed(with(any(IoSessionEx.class)));
                will(new CustomAction("Latch countdown") {
                    @Override
                    public Object invoke(Invocation invocation) throws Throwable {
                        latch.countDown();
                        return null;
                    }
                });
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/echo", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
        assertTrue(latch.await(10, SECONDS));
        context.assertIsSatisfied();
    }

    @Test
    @Specification({
        "server.send.opcode.0x04/handshake.response.and.frame" })
    public void shouldFailWebSocketConnectionWhenServerSendOpcode4Frame() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);
        final CountDownLatch latch = new CountDownLatch(1);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                oneOf(handler).sessionClosed(with(any(IoSessionEx.class)));
                will(new CustomAction("Latch countdown") {
                    @Override
                    public Object invoke(Invocation invocation) throws Throwable {
                        latch.countDown();
                        return null;
                    }
                });
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/echo", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
        assertTrue(latch.await(10, SECONDS));
        context.assertIsSatisfied();
    }

    @Test
    @Specification({
        "server.send.opcode.0x05/handshake.response.and.frame" })
    public void shouldFailWebSocketConnectionWhenServerSendOpcode5Frame() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);
        final CountDownLatch latch = new CountDownLatch(1);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                oneOf(handler).sessionClosed(with(any(IoSessionEx.class)));
                will(new CustomAction("Latch countdown") {
                    @Override
                    public Object invoke(Invocation invocation) throws Throwable {
                        latch.countDown();
                        return null;
                    }
                });
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/echo", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
        assertTrue(latch.await(10, SECONDS));
        context.assertIsSatisfied();
    }

    @Test
    @Specification({
        "server.send.opcode.0x06/handshake.response.and.frame" })
    public void shouldFailWebSocketConnectionWhenServerSendOpcode6Frame() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);
        final CountDownLatch latch = new CountDownLatch(1);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                oneOf(handler).sessionClosed(with(any(IoSessionEx.class)));
                will(new CustomAction("Latch countdown") {
                    @Override
                    public Object invoke(Invocation invocation) throws Throwable {
                        latch.countDown();
                        return null;
                    }
                });
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/echo", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
        assertTrue(latch.await(10, SECONDS));
        context.assertIsSatisfied();
    }

    @Test
    @Specification({
        "server.send.opcode.0x07/handshake.response.and.frame" })
    public void shouldFailWebSocketConnectionWhenServerSendOpcode7Frame() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);
        final CountDownLatch latch = new CountDownLatch(1);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                oneOf(handler).sessionClosed(with(any(IoSessionEx.class)));
                will(new CustomAction("Latch countdown") {
                    @Override
                    public Object invoke(Invocation invocation) throws Throwable {
                        latch.countDown();
                        return null;
                    }
                });
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/echo", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
        assertTrue(latch.await(10, SECONDS));
        context.assertIsSatisfied();
    }
}


text:
using System;

namespace OPC_server_subscription
{
    public class OpcItem
    {
        private object _value;
        public string Quality { get; set; }
        public string ItemName { get; set; }

        public object Value
        {
            get
            {
                return _value;
            }
            set
            {
                if (_value == value)
                {
                    return;
                }
                _value = value;
            }
        }
    }
}


text:
(function () {
  'use strict';

  angular
    .module('core')
    .controller('HomeController', HomeController);

  function HomeController($state, CrawledArticles, $scope, $q, $location, clipboard, $mdDialog, $http, Authentication, ngProgressFactory, $stateParams) {
    var vm = this;

    // This provides Authentication context.
    $scope.authentication = Authentication;
    $scope.resultArticles = [];
    $scope.progressbar = ngProgressFactory.createInstance();
    $scope.selected = [];

    $scope.toggle = function (item, list) {
      var idx = list.indexOf(item);
      if (idx > -1) {
        list.splice(idx, 1);
      } else {
        list.push(item);
      }

      console.log(JSON.stringify(list));
    };

    $scope.exists = function (item, list) {
      return list.indexOf(item) > -1;
    };

    $scope.displayArticleToHomepage = function () {
      // 선택된 기사 홈페이지에 올리기
      $scope.success = $scope.error = null;

      var deferred = $q.defer();
      if (Authentication.user) {
        var selected = $scope.selected;
        var total = selected.length;
        var done = 0;

        angular.forEach(selected, function (item) {
          var article = new CrawledArticles({
            keyword: $scope.searchKeyword,
            title: item.title,
            summary: item.summary,
            media: item.media,
            url: item.url,
            displayed: true,
            articleAt: item.article_at
          });

          article.$save(function (response) {
            console.log('success:' + response);
            if (++done === total)
              deferred.resolve();
          }, function (errorRespose) {
            $scope.error = errorRespose.data.message;
            console.log('failed: ' + $scope.error);
            console.log(JSON.stringify(errorRespose));
            deferred.reject();
          });
        });

        var confirm = $mdDialog.confirm()
          .textContent('홈페이지에 게시되었습니다. 홈페이지에 게시된 글을 확인시겠습니까?')
          .ok('예')
          .cancel('아니요');
        $mdDialog.show(confirm).then(function () {
          $state.go('monitoring.list');
        });
      }
    };

    $scope.closeDialog = function () {
      $mdDialog.hide();
    };

    $scope.shareArticle = function ($event) {
      // 선택된 기사 공유하기
      // : 제목과 링크로 구성된 문자열을 만들어 클립보드로 복사한다.
      var selected = $scope.selected;
      var text = '';
      angular.forEach(selected, function (item) {
        text += '
' + item.title + ' 더보기
';
      });
      console.log(text);

      clipboard.copyText(text);

      var alert = $mdDialog.alert()
        .title('기사링크가 복사되었습니다.')
        .htmlContent('<md-content>' + text + '</md-content>')
        .ok('닫기');

      $mdDialog
        .show(alert)
        .finally(function () {
          alert = undefined;
        });
    };

    $scope.goSearch = function () {
      console.log($stateParams.corpCode);
      if ($stateParams.corpCode !== undefined) {
        $scope.searchKeyword = $stateParams.corpCode;
      }
      console.log($scope.searchKeyword);

      $scope.resultArticles = [];
      $scope.progressbar.start();
      var req = {
        method: 'POST',
        url: '/search',
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        },
        data: { keyword: $scope.searchKeyword }
      };

      $http(req).then(function (res) {
        var jsonData = res;

        if (typeof(jsonData) === 'string') {
          // unit test시 json 변환후 string인경우 다시한번 변환한다.
          jsonData = JSON.parse(jsonData);
        }

        if (jsonData.status === 200) {
          $scope.resultArticles = jsonData.data;
        }

        $scope.progressbar.complete();
      }, function (err) {
        $scope.progressbar.complete();
        console.log(err.message);
      });

    };

    $scope.checkEnter = function ($event) {
      var keyCode = $event.which || $event.keyCode;
      if (keyCode === 13) {
        $scope.goSearch();
      }
    };
  }
}());