text:
package twitter4j.examples.block;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

/**
 * Unblocks the specified user.
 *
 * @author Yusuke Yamamoto - yusuke at mac.com
 */
public final class DestroyBlock {
    /**
     * Usage: java twitter4j.examples.block.DestroyBlock [screen name]
     *
     * @param args message
     */
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java twitter4j.examples.block.DestroyBlock [screen name]");
            System.exit(-1);
        }
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.destroyBlock(args[0]);
            System.out.println("Successfully unblocked user [" + args[0] + "].");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to unblock user: " + te.getMessage());
            System.exit(-1);
        }
    }
}


text: Sexy crypto bot <3

redpajama_set_name: RedPajamaGithub


text:
$(function() {
	window.parent.pagetag && window.parent.pagetag.iframeLoaded(window._tgId, function(sampleData) {
		window.frameElement.style.display = "block";
		window.frameElement.previousSibling.style.display = "none";
		if (sampleData.header) {
			$(document.head)[sampleData.action||"html"](sampleData.header + "\n")
		}
		if (sampleData.html) {
			$(document.body).html(sampleData.html);
		}
		try {
			if (sampleData.code) {
				for (var tmpl in $.templates) {
					delete $.templates[tmpl];
				}
				(new Function(sampleData.code))();
			}
			if (sampleData.markup) {
				if (sampleData.jsrJsvJqui === "jsr") {
					$('#result').html($.templates(sampleData.markup).render(sampleData.data));
				} else {
					$.templates(sampleData.markup).link('#result', sampleData.data);
				}
			}
		} catch(e) {
			(sampleData.markup ? $('#result') : $('body')).html(
				"Error in sample. <button onclick='$(\"#details\").toggle()'>details</button>
"
				+ $.views.converters.html(e.message||e) + "
"
			);
		}
	});
});


text:
subroutine report_close( report  )

    type(report_data) :: report

    select case( report%type )
        case( report_rtf )
            call report_close_rtf( report%rtf  )
        case( report_html )
            call report_close_html( report%html  )
        case( report_latex )
            call report_close_latex( report%latex  )
    end select
end subroutine report_close

subroutine report_text( report , text )

    type(report_data) :: report

    character(len=*), dimension(:) :: text

    select case( report%type )
        case( report_rtf )
            call report_text_rtf( report%rtf , text )
        case( report_html )
            call report_text_html( report%html , text )
        case( report_latex )
            call report_text_latex( report%latex , text )
    end select
end subroutine report_text

subroutine report_newpar( report  )

    type(report_data) :: report

    select case( report%type )
        case( report_rtf )
            call report_newpar_rtf( report%rtf  )
        case( report_html )
            call report_newpar_html( report%html  )
        case( report_latex )
            call report_newpar_latex( report%latex  )
    end select
end subroutine report_newpar

subroutine report_chapter( report , title )

    type(report_data) :: report

    character(len=*)                 :: title

    select case( report%type )
        case( report_rtf )
            call report_chapter_rtf( report%rtf , title )
        case( report_html )
            call report_chapter_html( report%html , title )
        case( report_latex )
            call report_chapter_latex( report%latex , title )
    end select
end subroutine report_chapter

subroutine report_section( report , title )

    type(report_data) :: report

    character(len=*)                 :: title

    select case( report%type )
        case( report_rtf )
            call report_section_rtf( report%rtf , title )
        case( report_html )
            call report_section_html( report%html , title )
        case( report_latex )
            call report_section_latex( report%latex , title )
    end select
end subroutine report_section

subroutine report_subsection( report , title )

    type(report_data) :: report

    character(len=*)                 :: title

    select case( report%type )
        case( report_rtf )
            call report_subsection_rtf( report%rtf , title )
        case( report_html )
            call report_subsection_html( report%html , title )
        case( report_latex )
            call report_subsection_latex( report%latex , title )
    end select
end subroutine report_subsection

subroutine report_emph( report , text )

    type(report_data) :: report

    character(len=*)                 :: text

    select case( report%type )
        case( report_rtf )
            call report_emph_rtf( report%rtf , text )
        case( report_html )
            call report_emph_html( report%html , text )
        case( report_latex )
            call report_emph_latex( report%latex , text )
    end select
end subroutine report_emph

subroutine report_verbatim( report , verbatim )

    type(report_data) :: report

    logical                          :: verbatim

    select case( report%type )
        case( report_rtf )
            call report_verbatim_rtf( report%rtf , verbatim )
        case( report_html )
            call report_verbatim_html( report%html , verbatim )
        case( report_latex )
            call report_verbatim_latex( report%latex , verbatim )
    end select
end subroutine report_verbatim

subroutine report_table_begin( report , header )

    type(report_data) :: report

    character(len=*), dimension(:)   :: header

    select case( report%type )
        case( report_rtf )
            call report_table_begin_rtf( report%rtf , header )
        case( report_html )
            call report_table_begin_html( report%html , header )
        case( report_latex )
            call report_table_begin_latex( report%latex , header )
    end select
end subroutine report_table_begin

subroutine report_table_row( report , data )

    type(report_data) :: report

    character(len=*), dimension(:)   :: data

    select case( report%type )
        case( report_rtf )
            call report_table_row_rtf( report%rtf , data )
        case( report_html )
            call report_table_row_html( report%html , data )
        case( report_latex )
            call report_table_row_latex( report%latex , data )
    end select
end subroutine report_table_row

subroutine report_table_end( report  )

    type(report_data) :: report

    select case( report%type )
        case( report_rtf )
            call report_table_end_rtf( report%rtf  )
        case( report_html )
            call report_table_end_html( report%html  )
        case( report_latex )
            call report_table_end_latex( report%latex  )
    end select
end subroutine report_table_end

subroutine report_list_begin( report  )

    type(report_data) :: report

    select case( report%type )
        case( report_rtf )
            call report_list_begin_rtf( report%rtf  )
        case( report_html )
            call report_list_begin_html( report%html  )
        case( report_latex )
            call report_list_begin_latex( report%latex  )
    end select
end subroutine report_list_begin

subroutine report_list_end( report  )

    type(report_data) :: report

    select case( report%type )
        case( report_rtf )
            call report_list_end_rtf( report%rtf  )
        case( report_html )
            call report_list_end_html( report%html  )
        case( report_latex )
            call report_list_end_latex( report%latex  )
    end select
end subroutine report_list_end

subroutine report_list_item( report , text )

    type(report_data) :: report

    character(len=*), dimension(:)   :: text

    select case( report%type )
        case( report_rtf )
            call report_list_item_rtf( report%rtf , text )
        case( report_html )
            call report_list_item_html( report%html , text )
        case( report_latex )
            call report_list_item_latex( report%latex , text )
    end select
end subroutine report_list_item


text:
"""
UserBot module
Copyright 2015, Ismael R. Lugo G.
"""

import admin
reload(admin)

from sysb import commands
from admin import lang
from admin import _

commands.addHandler('admin', 'admin id (?P<name>[^ ]+) (?P<passwd>[^ ]+)', {
    'sintax': 'admin id <name> <password>',
    'example': 'admin id root 1234',
    'desc': _('identifica a un usuario como operador en userbot', lang)},
    registered=True,
    logged=True)(admin.operid)

commands.addHandler('admin', 'admin lock (?P<account>[^ ]+) (?P<reason>.*)', {
    'sintax': 'admin lock <account> <reason>',
    'example': 'admin lock fooser bad boy',
    'desc': _('bloquea a un usuario en userbot', lang)},
    registered=True,
    oper=('local', 'global'),
    logged=True)(admin.lock_user)

commands.addHandler('admin', 'admin unlock (?P<account>[^ ]+)', {
    'sintax': 'admin unlock <account>',
    'example': 'admin unlock fooser',
    'desc': _('desbloquea a un usuario en userbot', lang)},
    oper=('local', 'global'),
    registered=True,
    logged=True)(admin.unlock_user)

commands.addHandler('admin', 'admin flags (?P<channel>[^ ]+) (?P<target>[^ ]+) (?P<flags>[^ ]+)', {
    'sintax': 'admin flags <channel> <target> <flags/template>',
    'example': 'admin flags #Foo fooser founder',
    'desc': _('fuerza el cambio de flags en un canal', lang)},
    oper=('noob', 'local', 'global'),
    logged=True,
    registered=True,
    channels=True,
    chn_registered=True,
    chan_reqs='channel')(admin.flags)

commands.addHandler('admin', 'admin add (?P<level>[^ ]+) (?P<name>[^ ]+) (?P<sh'
    'a_passwd>[^ ]+)', {'sintax': 'admin add <level> <name> <sha_passwd>',
    'example': 'admin add local/freenode root 81dc9bdb52d04dc20036dbd8313ed055',
    'desc': (
        _('añade un nuevo operador de userbot segun el nivel dado', lang),
        _('niveles disponibles: global local/servidor noob/servidor', lang))},
    oper=('global',),
    registered=True,
    logged=True)(admin.addoper)

commands.addHandler('admin', 'admin del (?P<name>[^ ]+)', {
    'sintax': 'admin del <name>',
    'example': 'admin del root',
    'desc': _('elimina un operador de userbot', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.deloper)

commands.addHandler('admin', 'admin load (?P<module>[^ ]+)', {
    'sintax': 'admin load <module>',
    'example': 'admin load users.py',
    'desc': _('carga un modulo a userbot', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.load_module)

commands.addHandler('admin', 'admin download (?P<module>[^ ]+)', {
    'sintax': 'admin download <module>',
    'example': 'admin download users.py',
    'desc': _('descarga un modulo de userbot', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.download_module)

commands.addHandler('admin', 'admin join (?P<channel>[^ ]+)( (?P<passwd>[^ ]+))?', {
    'sintax': 'admin join <channel> <password>?',
    'example': 'admin join #Foo',
    'desc': _('ingresa userbot a un canal', lang)},
    oper=('noob', 'local', 'global'),
    registered=True,
    logged=True)(admin.join)

commands.addHandler('admin', 'admin mode (?P<target>[^ ]+) (?P<mode>.*)', {
    'sintax': 'admin mode <target> <mode>',
    'example': 'admin mode #Foo +b *!*@localhost',
    'desc': _('establece un modo de canal / usuario', lang)},
    oper=('local', 'global'),
    registered=True,
    logged=True)(admin.mode)

commands.addHandler('admin', 'admin say (?P<target>[^ ]+) (?P<message>.*)', {
    'sintax': 'admin say <target> <message>',
    'example': 'admin say #Foo Hi!',
    'desc': _('envia un mensaje equis a traves de userbot', lang)},
    oper=('local', 'global'),
    registered=True,
    logged=True)(admin.say)

commands.addHandler('admin', 'admin connect (?P<servername>[^ ]+)', {
    'sintax': 'admin connect <servername>',
    'example': 'admin connect localhost',
    'desc': _('conecta a userbot a un servidor especificado', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.connect_to)

commands.addHandler('admin', 'admin disconnect (?P<servername>[^ ]+)', {
    'sintax': 'admin disconnect <servername>',
    'example': 'admin disconnect localhost',
    'desc': _('desconecta a userbot de un servidor', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.disconnect_to)

commands.addHandler('admin', 'admin exec (?P<code>.*)', {
    'sintax': 'admin exec <code>',
    'example': 'admin exec ", ".join(commands.commands.modules.keys())',
    'desc': _('ejecuta codigo Python y responde lo retornado', lang)},
    oper=('global',),
    registered=True,
    logged=True)(admin.execute)

commands.addHandler('admin', 'admin uptime', {
    'sintax': 'admin uptime',
    'example': 'admin uptime',
    'desc': _('muestra el tiempo de actividad', lang)},
    oper=('local', 'global'),
    registered=True,
    logged=True)(admin.uptime)

commands.addHandler('admin', 'admin nick (?P<newnick>[^ ]+)', {
    'sintax': 'admin nick <newnick>',
    'example': 'admin nick Super_UserBot',
    'desc': _('cambia de nick', lang)},
    oper=('local', 'global'),
    registered=True,
    logged=True)(admin.nick)


text:
<?php

namespace bfday\PHPDailyFunctions\Bitrix\Helpers;

use bfday\PHPDailyFunctions\Traits\Cache\MethodResult;
use bfday\PHPDailyFunctions\Traits\Singleton;
use Bitrix\Iblock\IblockTable;
use Bitrix\Main\Entity\Query;
use Bitrix\Main\Loader;

/**
 * IBlock helper to help in common routines.
 *
 * @method static |IBlock getInstance()
 */
class IBlock
{
    use Singleton;
    use MethodResult;

    /**
     * @var string - path to cache dir. relative to /bitrix/cache or absolute to system.
     */
    protected $cacheDir;

    /**
     * Returns IBlocks IDs by their codes. Uses Bitrix D7
     * Warning: all IBlock codes should be unique in all DB.
     *
     * @param $codes array|string
     *
     * @return array of string|bool
     * @throws \Exception
     */
    public function getIBlockIDsByCodes($codes)
    {
        if (empty($codes)) {
            throw new \Exception('$codes cannot be empty.');
        } elseif (is_array($codes)) {
            // remove duplicate codes or throw exception?
            if (count($codes) != count(array_unique($codes))) {
                throw new \Exception('$codes cannot contain duplicate values.');
            }
            // maybe resort is needed to exclude similar cache ids
            sort($codes);
        } elseif (!is_array($codes)) {
            if (is_string($codes) || is_int($codes)) {
                $codes = [$codes];
            } else {
                throw new \Exception('$codes must have string, integer or array type.');
            }
        }

        Loader::includeModule('iblock');

        if (($arIBlockCodesIDs = $this->cacheSetStorageProvider(new \CPHPCache())
                                      ->setCacheTime(8640000)
                                      ->cacheGetData(__METHOD__, null, $codes)) === null
        ) {
            $arIBlockCodesIDs = [];

            if (!empty($codes)) {
                $query = new Query(IblockTable::getEntity());
                $arIBlocks = $query
                    ->setFilter([
                        'CODE' => $codes,
                    ])
                    ->setSelect([
                        'ID',
                        'CODE',
                    ])
                    ->exec()
                    ->fetchAll()
                ;
                foreach ($arIBlocks as $arIBlock) {
                    if (isset($arIBlockCodesIDs[$arIBlock['CODE']])) {
                        throw new \Exception("There more than 1 IBlock with CODE={$arIBlock['CODE']}. This function works only when all IBlocks have unique codes.");
                    }
                    $arIBlockCodesIDs[$arIBlock['CODE']] = $arIBlock['ID'];
                    if (($k = array_search($arIBlock['CODE'], $codes)) !== false) {
                        unset($codes[$k]);
                    }
                }
                unset($arIBlocks);
            }

            if (!empty($codes)) {
                foreach ($codes as $code) {
                    $arIBlockCodesIDs[$code] = false;
                }
            }

            $this->cacheSaveData($arIBlockCodesIDs);
        }

        return $arIBlockCodesIDs;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Mauricio
 * Date: 12/05/14
 * Time: 22:28
 */

namespace prog3\AppunteBundle\Controller;

use prog3\AppunteBundle\Entity\Usuario;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class RegisterController extends Controller {

    /**
     * @Template
     */
    public function registerAction(Request $request)
    {
       $form = $this->createFormBuilder()
            ->add('username', 'text')
            ->add('password', 'repeated', array(
                    'type' => 'password',
           ))
            ->add('email', 'email')
            ->add('nombre', 'text')
            ->add('apellido', 'text')
            ->getForm()
        ;

        if ($request->isMethod('POST')) {
            $form->bind($request);

            if ($form->isValid()) {
                $data = $form->getData();

                $user = new Usuario();
                $user->setUsername($data['username']);
                $user->setEmail($data['email']);
                $user->setNombre($data['nombre']);
                $user->setApellido($data['apellido']);
                $user->setPassword($this->encodePassword($user, $data['password']));

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $url = $this->generateUrl('login');

                return $this->redirect($url);

            }
        }

        return array('form' => $form->createView());
    }

    private function encodePassword($usuario, $plainPassword)
    {
        $encoder = $this->container->get('security.encoder_factory')
            ->getEncoder($usuario)
        ;

        return $encoder->encodePassword($plainPassword, $usuario->getSalt());
    }

}


text:
This is the code for the coding challenge presented by Crowe Horwath during their interview process

Spec:

Write a Hello World program – use .NET Technologies to complete<

The program has 1 current business requirement a write Hello World to the console/screen.

The program should have an API that is separated from the program logic to eventually support mobile applications, web applications, console applications or windows services.

The program should support future enhancements for writing to a database, console application, etc.

Use common design patterns (inheritance, e.g.) to account for these future concerns.

Use configuration files or another industry standard mechanism for determining where to write the information to.

Write unit tests to support the API.

Running it:

The program contains is broken up into a few libraries.

HelloWorld.ConsoleClient: A console application that interacts with an IMessageService.  The console will give the user
  the ability to add, delete, and view messages.

HelloWorld.WebApi: A web api application that interacts with an IMessageService.  The api exposes endpoints that allow
  the user to add, delete, and view messsages.

HelloWorld.WebApi.Test: Unit tests for the HelloWorld.WebApi project

HelloWorld.MemoryDataStore: A simple in memory data storage library for holding created messages. Contains an implementation
  for the IMessageDataStore.

HelloWorld.Contracts: Contains all the contracts needed for interaction between the layers.

HelloWorld.Service: A service layer library that connects to an IMessageDataStore for persisting and retrieving messages.

HelloWorld.Service.Tests: Unit tests for the HelloWorld.Service library

IOC Notes: The console application uses the Unity framework for IOC\DI.  The registrations are located in the app.config.
The WebApi application also uses Unity.  Its registrations are done in the ContainerBootstrapper class.  I wanted to show two different "industry standard" ways of implementing IOC.  The test libraries inject their own custom interface implentations in order to efficiently test the methods while avoiding unwanted side effects.

Client Notes: I went with not making the WebApi application act as the true service layer because I didnt want the extra overhead involved.  Especially since the spec wanted one of the clients to be a console application.  Using a library instead of communicating over http seemed like a much more efficent route.  By doing this there is the added benefit of being able to customize the security depending on the propsed client. I.e. someone using the console application may not want security however, someone using a mobile application talking to WebApi might want some type of oauth authentication (just an example).

Other notes:  Should be easy to see that all layers are entierly swappable.  As long as the contract for the layer is met.  All necessary contracts are found in the HelloWorld.Contracts library.  I have implented this swappable architecture a few different ways.  I find this way the most efficient when your goal is to provide maximum swappability. For the dal all that is needed is something that implements the IMessageDataStore contract.  Obviously as the application was built out, more data contracts would be added.  A more generic pattern would be used as the application evolved.  For the service layer all that is needed is an IMessageService implementation.  This application contains two of each. One version to which the uses and one version for the testing libraries.


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file was forked off the Mac port.

#include "webkit/tools/test_shell/test_webview_delegate.h"

#include <gtk/gtk.h>
#include <gdk/gdkx.h>

#include "base/bind.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/gfx/gtk_util.h"
#include "ui/gfx/point.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/plugins/npapi/gtk_plugin_container_manager.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugin.h"
#include "webkit/plugins/npapi/webplugin_delegate_impl.h"
#include "webkit/tools/test_shell/test_navigation_controller.h"
#include "webkit/tools/test_shell/test_shell.h"

using WebKit::WebCursorInfo;
using WebKit::WebFrame;
using WebKit::WebNavigationPolicy;
using WebKit::WebPopupMenuInfo;
using WebKit::WebRect;
using WebKit::WebWidget;
using WebKit::WebView;

namespace {

enum SelectionClipboardType {
  TEXT_HTML,
  PLAIN_TEXT,
};

GdkAtom GetTextHtmlAtom() {
  GdkAtom kTextHtmlGdkAtom = gdk_atom_intern_static_string("text/html");
  return kTextHtmlGdkAtom;
}

void SelectionClipboardGetContents(GtkClipboard* clipboard,
    GtkSelectionData* selection_data, guint info, gpointer data) {
  // Ignore formats that we don't know about.
  if (info != TEXT_HTML && info != PLAIN_TEXT)
    return;

  WebView* webview = static_cast<WebView*>(data);
  WebFrame* frame = webview->focusedFrame();
  if (!frame)
    frame = webview->mainFrame();
  DCHECK(frame);

  std::string selection;
  if (TEXT_HTML == info) {
    selection = frame->selectionAsMarkup().utf8();
  } else {
    selection = frame->selectionAsText().utf8();
  }
  if (TEXT_HTML == info) {
    gtk_selection_data_set(selection_data,
                           GetTextHtmlAtom(),
                           8 /* bits per data unit, ie, char */,
                           reinterpret_cast<const guchar*>(selection.data()),
                           selection.length());
  } else {
    gtk_selection_data_set_text(selection_data, selection.data(),
        selection.length());
  }
}

}  // namespace

// WebViewClient --------------------------------------------------------------

WebWidget* TestWebViewDelegate::createPopupMenu(
    const WebPopupMenuInfo& info) {
  NOTREACHED();
  return NULL;
}

// WebWidgetClient ------------------------------------------------------------

void TestWebViewDelegate::show(WebNavigationPolicy policy) {
  WebWidgetHost* host = GetWidgetHost();
  GtkWidget* drawing_area = host->view_handle();
  GtkWidget* window =
      gtk_widget_get_parent(gtk_widget_get_parent(drawing_area));
  gtk_widget_show_all(window);
}

void TestWebViewDelegate::closeWidgetSoon() {
  if (this == shell_->delegate()) {
    MessageLoop::current()->PostTask(
        FROM_HERE,
        base::Bind(&gtk_widget_destroy, GTK_WIDGET(shell_->mainWnd())));
  } else if (this == shell_->popup_delegate()) {
    shell_->ClosePopup();
  }
}

void TestWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) {
  current_cursor_.InitFromCursorInfo(cursor_info);
  GdkCursorType cursor_type =
      static_cast<GdkCursorType>(current_cursor_.GetCursorType());
  GdkCursor* gdk_cursor;
  if (cursor_type == GDK_CURSOR_IS_PIXMAP) {
    // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is
    // that calling gdk_window_set_cursor repeatedly is expensive.  We should
    // avoid it here where possible.
    gdk_cursor = current_cursor_.GetCustomCursor();
  } else {
    // Optimize the common case, where the cursor hasn't changed.
    // However, we can switch between different pixmaps, so only on the
    // non-pixmap branch.
    if (cursor_type_ == cursor_type)
      return;
    if (cursor_type == GDK_LAST_CURSOR)
      gdk_cursor = NULL;
    else
      gdk_cursor = gfx::GetCursor(cursor_type);
  }
  cursor_type_ = cursor_type;
  gdk_window_set_cursor(shell_->webViewWnd()->window, gdk_cursor);
}

WebRect TestWebViewDelegate::windowRect() {
  WebWidgetHost* host = GetWidgetHost();
  GtkWidget* drawing_area = host->view_handle();
  GtkWidget* vbox = gtk_widget_get_parent(drawing_area);
  GtkWidget* window = gtk_widget_get_parent(vbox);

  gint x, y;
  gtk_window_get_position(GTK_WINDOW(window), &x, &y);
  x += vbox->allocation.x + drawing_area->allocation.x;
  y += vbox->allocation.y + drawing_area->allocation.y;

  return WebRect(x, y,
                 drawing_area->allocation.width,
                 drawing_area->allocation.height);
}

void TestWebViewDelegate::setWindowRect(const WebRect& rect) {
  if (this == shell_->delegate()) {
    set_fake_window_rect(rect);
  } else if (this == shell_->popup_delegate()) {
    WebWidgetHost* host = GetWidgetHost();
    GtkWidget* drawing_area = host->view_handle();
    GtkWidget* window =
        gtk_widget_get_parent(gtk_widget_get_parent(drawing_area));
    gtk_window_resize(GTK_WINDOW(window), rect.width, rect.height);
    gtk_window_move(GTK_WINDOW(window), rect.x, rect.y);
  }
}

WebRect TestWebViewDelegate::rootWindowRect() {
  if (using_fake_rect_) {
    return fake_window_rect();
  }
  if (WebWidgetHost* host = GetWidgetHost()) {
    // We are being asked for the x/y and width/height of the entire browser
    // window.  This means the x/y is the distance from the corner of the
    // screen, and the width/height is the size of the entire browser window.
    // For example, this is used to implement window.screenX and window.screenY.
    GtkWidget* drawing_area = host->view_handle();
    GtkWidget* window =
        gtk_widget_get_parent(gtk_widget_get_parent(drawing_area));
    gint x, y, width, height;
    gtk_window_get_position(GTK_WINDOW(window), &x, &y);
    gtk_window_get_size(GTK_WINDOW(window), &width, &height);
    return WebRect(x, y, width, height);
  }
  return WebRect();
}

WebRect TestWebViewDelegate::windowResizerRect() {
  // Not necessary on Linux.
  return WebRect();
}

void TestWebViewDelegate::runModal() {
  NOTIMPLEMENTED();
}

// WebPluginPageDelegate ------------------------------------------------------

webkit::npapi::WebPluginDelegate* TestWebViewDelegate::CreatePluginDelegate(
    const FilePath& path,
    const std::string& mime_type) {
  // TODO(evanm): we probably shouldn't be doing this mapping to X ids at
  // this level.
  GdkNativeWindow plugin_parent =
      GDK_WINDOW_XWINDOW(shell_->webViewHost()->view_handle()->window);

  return webkit::npapi::WebPluginDelegateImpl::Create(
      path, mime_type, plugin_parent);
}

void TestWebViewDelegate::CreatedPluginWindow(
    gfx::PluginWindowHandle id) {
  shell_->webViewHost()->CreatePluginContainer(id);
}

void TestWebViewDelegate::WillDestroyPluginWindow(
    gfx::PluginWindowHandle id) {
  shell_->webViewHost()->DestroyPluginContainer(id);
}

void TestWebViewDelegate::DidMovePlugin(
    const webkit::npapi::WebPluginGeometry& move) {
  WebWidgetHost* host = GetWidgetHost();
  webkit::npapi::GtkPluginContainerManager* plugin_container_manager =
      static_cast<WebViewHost*>(host)->plugin_container_manager();
  plugin_container_manager->MovePluginContainer(move);
}

// Public methods -------------------------------------------------------------

void TestWebViewDelegate::UpdateSelectionClipboard(bool is_empty_selection) {
  if (is_empty_selection)
    return;

  GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
  // Put data on the X clipboard.  This doesn't actually grab the text from
  // the HTML, it just registers a callback for when someone tries to paste.
  GtkTargetList* target_list = gtk_target_list_new(NULL, 0);
  gtk_target_list_add(target_list, GetTextHtmlAtom(), 0, TEXT_HTML);
  gtk_target_list_add_text_targets(target_list, PLAIN_TEXT);

  gint num_targets = 0;
  GtkTargetEntry* targets = gtk_target_table_new_from_list(target_list,
                                                           &num_targets);
  gtk_clipboard_set_with_data(clipboard, targets, num_targets,
                              SelectionClipboardGetContents, NULL,
                              shell_->webView());
  gtk_target_list_unref(target_list);
  gtk_target_table_free(targets, num_targets);
}

// Private methods ------------------------------------------------------------

void TestWebViewDelegate::ShowJavaScriptAlert(const string16& message) {
  GtkWidget* dialog = gtk_message_dialog_new(
      shell_->mainWnd(), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO,
      GTK_BUTTONS_OK, "%s", UTF16ToUTF8(message).c_str());
  gtk_window_set_title(GTK_WINDOW(dialog), "JavaScript Alert");
  gtk_dialog_run(GTK_DIALOG(dialog));  // Runs a nested message loop.
  gtk_widget_destroy(dialog);
}

void TestWebViewDelegate::SetPageTitle(const string16& title) {
  gtk_window_set_title(GTK_WINDOW(shell_->mainWnd()),
                       ("Test Shell - " + UTF16ToUTF8(title)).c_str());
}

void TestWebViewDelegate::SetAddressBarURL(const GURL& url) {
  gtk_entry_set_text(GTK_ENTRY(shell_->editWnd()), url.spec().c_str());
}


text:
namespace asf = foundation;
namespace asr = renderer;

EnvLightExporter::EnvLightExporter(
    const MDagPath&                             path,
    asr::Project&                               project,
    AppleseedSession::SessionMode               sessionMode)
  : DagNodeExporter(path, project, sessionMode)
{
}

EnvLightExporter::~EnvLightExporter()
{
    if (sessionMode() == AppleseedSession::ProgressiveRenderSession)
    {
        scene().environment_shaders().remove(m_envShader.get());
        scene().environment_edfs().remove(m_envLight.get());
    }
}

void EnvLightExporter::createEntities(
    const AppleseedSession::Options&                options,
    const AppleseedSession::MotionBlurSampleTimes&  motionBlurSampleTimes)
{
    const asr::EnvironmentShaderFactoryRegistrar& factoryRegistrar =
        project().get_factory_registrar<asr::EnvironmentShader>();

    const asr::IEnvironmentShaderFactory* factory =
        factoryRegistrar.lookup("edf_environment_shader");

    MString envShaderName = appleseedName() + "_shader";
    m_envShader = factory->create(
        envShaderName.asChar(),
        asr::ParamArray().insert(
            "environment_edf",
            appleseedName().asChar()));
}

void EnvLightExporter::flushEntities()
{
    if (m_envLight.get())
        scene().environment_edfs().insert(m_envLight.release());

    if (m_envShader.get())
        scene().environment_shaders().insert(m_envShader.release());
}

void PhysicalSkyLightExporter::registerExporter()
{
    NodeExporterFactory::registerDagNodeExporter(
        PhysicalSkyLightNode::nodeName,
        &PhysicalSkyLightExporter::create);
}

DagNodeExporter* PhysicalSkyLightExporter::create(
    const MDagPath&                                 path,
    asr::Project&                                   project,
    AppleseedSession::SessionMode                   sessionMode)
{
    if (areObjectAndParentsRenderable(path) == false)
        return nullptr;

    return new PhysicalSkyLightExporter(path, project, sessionMode);
}

PhysicalSkyLightExporter::PhysicalSkyLightExporter(
    const MDagPath&                                 path,
    asr::Project&                                   project,
    AppleseedSession::SessionMode                   sessionMode)
  : EnvLightExporter(path, project,                 sessionMode)
{
}

PhysicalSkyLightExporter::~PhysicalSkyLightExporter()
{
    if (sessionMode() == AppleseedSession::ProgressiveRenderSession)
    {
        if (m_sunLight.get())
            mainAssembly().lights().remove(m_sunLight.get());
    }
}

void PhysicalSkyLightExporter::createEntities(
    const AppleseedSession::Options&                options,
    const AppleseedSession::MotionBlurSampleTimes&  motionBlurSampleTimes)
{
    asr::ParamArray params;
    MAngle angle;
    float val;

    AttributeUtils::get(node(), "sunTheta", angle);
    params.insert("sun_theta", angle.asDegrees());

    AttributeUtils::get(node(), "sunPhi", angle);
    params.insert("sun_phi", angle.asDegrees());

    AttributeUtils::get(node(), "turbidityScale", val);
    params.insert("turbidity_multiplier", val);

    AttributeUtils::get(node(), "luminanceScale", val);
    params.insert("luminance_multiplier", val);

    AttributeUtils::get(node(), "luminanceGamma", val);
    params.insert("luminance_gamma", val);

    AttributeUtils::get(node(), "saturationScale", val);
    params.insert("saturation_multiplier", val);

    AttributeUtils::get(node(), "horizonShift", angle);
    params.insert("horizon_shift", angle.asDegrees());

    AttributeUtils::get(node(), "groundAlbedo", val);
    params.insert("ground_albedo", val);

    float turbidity = 4.0f;
    AttributeUtils::get(node(), "turbidity", turbidity);
    params.insert("turbidity", turbidity);

    m_envLight = asr::HosekEnvironmentEDFFactory().create(
        appleseedName().asChar(),
        params);

    EnvLightExporter::createEntities(options, motionBlurSampleTimes);

    bool sunEnabled = false;
    AttributeUtils::get(node(), "sunEnable", sunEnabled);
    if (sunEnabled)
    {
        float radianceScale = 1.0f;
        AttributeUtils::get(node(), "sunRadianceScale", radianceScale);

        float sizeScale = 1.0f;
        AttributeUtils::get(node(), "sunSizeScale", sizeScale);

        MString name = appleseedName();
        name += "_sun_light";

        m_sunLight = asr::SunLightFactory().create(
            name.asChar(),
            asr::ParamArray()
                .insert("environment_edf", appleseedName().asChar())
                .insert("turbidity", turbidity)
                .insert("radiance_multiplier", radianceScale)
                .insert("size_multiplier", sizeScale));
    }
}

void PhysicalSkyLightExporter::flushEntities()
{
    EnvLightExporter::flushEntities();

    if (m_sunLight.get())
        mainAssembly().lights().insert(m_sunLight.release());
}

void SkyDomeLightExporter::registerExporter()
{
    NodeExporterFactory::registerDagNodeExporter(
        SkyDomeLightNode::nodeName,
        &SkyDomeLightExporter::create);
}

DagNodeExporter* SkyDomeLightExporter::create(
    const MDagPath&                                 path,
    asr::Project&                                   project,
    AppleseedSession::SessionMode                   sessionMode)
{
    if (areObjectAndParentsRenderable(path) == false)
        return nullptr;

    return new SkyDomeLightExporter(path, project, sessionMode);
}

SkyDomeLightExporter::SkyDomeLightExporter(
    const MDagPath&                                 path,
    asr::Project&                                   project,
    AppleseedSession::SessionMode                   sessionMode)
  : EnvLightExporter(path, project,                 sessionMode)
{
}

SkyDomeLightExporter::~SkyDomeLightExporter()
{
    if (sessionMode() == AppleseedSession::ProgressiveRenderSession)
    {
        if (m_mapTexture.get())
            scene().textures().remove(m_mapTexture.get());

        if (m_mapTextureInstance.get())
            scene().texture_instances().remove(m_mapTextureInstance.get());
    }
}

void SkyDomeLightExporter::createEntities(
    const AppleseedSession::Options&                options,
    const AppleseedSession::MotionBlurSampleTimes&  motionBlurSampleTimes)
{
    asr::ParamArray params;

    MString map;
    float val;
    MAngle angle;

    AttributeUtils::get(node(), "map", map);
    MString textureName = appleseedName() + "_texture";
    m_mapTexture = asr::DiskTexture2dFactory().create(
        textureName.asChar(),
        asr::ParamArray()
            .insert("filename", map.asChar())
            .insert("color_space", "linear_rgb"),
        project().search_paths());

    MString textureInstanceName = textureName + "_instance";
    m_mapTextureInstance = asr::TextureInstanceFactory().create(
        textureInstanceName.asChar(),
        asr::ParamArray(),
        textureName.asChar());
    params.insert("radiance", textureInstanceName.asChar());

    AttributeUtils::get(node(), "intensity", val);
    params.insert("radiance_multiplier", val);

    AttributeUtils::get(node(), "exposure", val);
    params.insert("exposure", val);

    AttributeUtils::get(node(), "hShift", angle);
    params.insert("horizontal_shift", angle.asDegrees());

    AttributeUtils::get(node(), "vShift", angle);
    params.insert("vertical_shift", angle.asDegrees());

    m_envLight = asr::LatLongMapEnvironmentEDFFactory().create(
        appleseedName().asChar(),
        params);

    EnvLightExporter::createEntities(options, motionBlurSampleTimes);
}

void SkyDomeLightExporter::exportTransformMotionStep(float time)
{
    asf::Matrix4d m = convert(dagPath().inclusiveMatrix());

    // Keep only the rotation components of the matrix.
    asf::Vector3d s, t;
    asf::Quaterniond r;
    m.decompose(s, r, t);
    m = asf::Matrix4d::make_rotation(r);

    asf::Transformd xform(m);
    m_envLight->transform_sequence().set_transform(time, xform);
}

void SkyDomeLightExporter::flushEntities()
{
    if (m_mapTexture.get())
        scene().textures().insert(m_mapTexture.release());

    if (m_mapTextureInstance.get())
        scene().texture_instances().insert(m_mapTextureInstance.release());

    EnvLightExporter::flushEntities();
}


text:
package org.jboss.aesh.extensions.mkdir;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.jboss.aesh.console.Config;
import org.jboss.aesh.extensions.common.AeshTestCommons;
import org.jboss.aesh.extensions.ls.Ls;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Helio Frota
 */
public class MkdirTest extends AeshTestCommons {

    private Path tempDir;
    private String aeshRocksDir;
    private String aeshRocksSubDir;

    @Before
    public void before() throws IOException {
        tempDir = createTempDirectory();

        aeshRocksDir = tempDir.toFile().getAbsolutePath() + Config.getPathSeparator() + "aesh_rocks";

        aeshRocksSubDir = tempDir.toFile().getAbsolutePath()
                + Config.getPathSeparator()
                + "aesh_rocks"
                + Config.getPathSeparator()
                + "subdir1"
                + Config.getPathSeparator()
                + "subdir2";

    }

    @Test
    public void testMkdir() throws IOException, InterruptedException {

        prepare(Mkdir.class, Ls.class);
        assertFalse(new File(aeshRocksDir).exists());
        pushToOutput("mkdir -v " + aeshRocksDir);
        assertTrue(new File(aeshRocksDir).exists());

        assertFalse(new File(aeshRocksSubDir).exists());
        pushToOutput("mkdir -p " + aeshRocksSubDir);
        assertTrue(new File(aeshRocksSubDir).exists());

        finish();
    }

    @After
    public void after() {
        try {
            Files.delete(new File(aeshRocksSubDir).toPath());
            Files.delete(new File(aeshRocksDir + Config.getPathSeparator() + "subdir1").toPath());
            Files.delete(new File(aeshRocksDir).toPath());
            Files.delete(tempDir);
        }
        catch(IOException ignored) {}
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Fixer\FunctionNotation;

use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\FunctionNotation\NativeFunctionInvocationFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;

/**
 * @author Andreas Möller <am@localheinz.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Fixer\FunctionNotation\NativeFunctionInvocationFixer
 */
final class NativeFunctionInvocationFixerTest extends AbstractFixerTestCase
{
    public function testConfigureRejectsUnknownConfigurationKey(): void
    {
        $key = 'foo';

        $this->expectException(InvalidConfigurationException::class);
        $this->expectExceptionMessage(sprintf(
            '[native_function_invocation] Invalid configuration: The option "%s" does not exist.',
            $key
        ));

        $this->fixer->configure([
            $key => 'bar',
        ]);
    }

    /**
     * @dataProvider provideInvalidConfigurationElementCases
     *
     * @param mixed $element
     */
    public function testConfigureRejectsInvalidConfigurationElement($element): void
    {
        $this->expectException(InvalidConfigurationException::class);
        $this->expectExceptionMessage(sprintf(
            'Each element must be a non-empty, trimmed string, got "%s" instead.',
            \is_object($element) ? \get_class($element) : \gettype($element)
        ));

        $this->fixer->configure([
            'exclude' => [
                $element,
            ],
        ]);
    }

    public function provideInvalidConfigurationElementCases(): array
    {
        return [
            'null' => [null],
            'false' => [false],
            'true' => [false],
            'int' => [1],
            'array' => [[]],
            'float' => [0.1],
            'object' => [new \stdClass()],
            'not-trimmed' => ['  is_string  '],
        ];
    }

    /**
     * @param string[] $include
     *
     * @dataProvider provideConfigureIncludeSetsCases
     */
    public function testConfigureIncludeSets(
        array $include,
        ?string $expectedExceptionClass = null,
        ?string $expectedExceptionMessage = null
    ): void {
        if (null !== $expectedExceptionClass) {
            $this->expectException($expectedExceptionClass);
            $this->expectExceptionMessageMatches(sprintf('#^%s$#', preg_quote($expectedExceptionMessage, '#')));
        }

        $this->fixer->configure(['include' => $include]);

        if (null === $expectedExceptionClass) {
            $this->addToAssertionCount(1);
        }
    }

    public function provideConfigureIncludeSetsCases(): array
    {
        return [
            [['foo', 'bar']],
            [[NativeFunctionInvocationFixer::SET_ALL]],
            [[NativeFunctionInvocationFixer::SET_ALL, 'bar']],
            [
                ['@xxx'],
                InvalidFixerConfigurationException::class,
                '[native_function_invocation] Invalid configuration: Unknown set "@xxx", known sets are "@all", "@internal", "@compiler_optimized".',
            ],
            [
                [' x '],
                InvalidFixerConfigurationException::class,
                '[native_function_invocation] Invalid configuration: Each element must be a non-empty, trimmed string, got "string" instead.',
            ],
        ];
    }

    public function testConfigureResetsExclude(): void
    {
        $this->fixer->configure([
            'exclude' => [
                'is_string',
            ],
        ]);

        $before = <<<'PHP'
<?php

namespace WithClassNotPrefixed;

class Bar
{
    public function baz($foo)
    {
        if (isset($foo)) {
            is_string($foo);
        }
    }
}
PHP;

        $after = <<<'PHP'
<?php

namespace WithClassNotPrefixed;

class Bar
{
    public function baz($foo)
    {
        if (isset($foo)) {
            \is_string($foo);
        }
    }
}
PHP;

        $this->doTest($before);

        $this->fixer->configure([]);

        $this->doTest($after, $before);
    }

    /**
     * @dataProvider provideFixWithDefaultConfigurationCases
     */
    public function testFixWithDefaultConfiguration(string $expected, ?string $input = null): void
    {
        $this->doTest($expected, $input);
    }

    public function provideFixWithDefaultConfigurationCases(): array
    {
        return [
            [
                '<?php

\is_string($foo);
',
            ],
            [
                '<?php

\is_string($foo);
',
                '<?php

is_string($foo);
',
            ],
            [
                '<?php

class Foo
{
    public function bar($foo)
    {
        return \is_string($foo);
    }
}
',
            ],
            [
                '<?php

json_encode($foo);
\strlen($foo);
',
                '<?php

json_encode($foo);
strlen($foo);
',
            ],
            [
                '<?php

class Foo
{
    public function bar($foo)
    {
        return \IS_STRING($foo);
    }
}
',
                '<?php

class Foo
{
    public function bar($foo)
    {
        return IS_STRING($foo);
    }
}
',
            ],
            'fix multiple calls in single code' => [
                '<?php

json_encode($foo);
\strlen($foo);
\strlen($foo);
',
                '<?php

json_encode($foo);
strlen($foo);
strlen($foo);
',
            ],
        ];
    }

    /**
     * @dataProvider provideFixWithConfiguredExcludeCases
     */
    public function testFixWithConfiguredExclude(string $expected, ?string $input = null): void
    {
        $this->fixer->configure([
            'exclude' => [
                'is_string',
            ],
        ]);

        $this->doTest($expected, $input);
    }

    public function provideFixWithConfiguredExcludeCases(): array
    {
        return [
            [
                '<?php

is_string($foo);
',
            ],
            [
                '<?php

class Foo
{
    public function bar($foo)
    {
        return is_string($foo);
    }
}
',
            ],
        ];
    }

    /**
     * @dataProvider provideFixWithNamespaceConfigurationCases
     */
    public function testFixWithNamespaceConfiguration(string $expected, ?string $input = null, string $scope = 'namespaced'): void
    {
        $this->fixer->configure(['scope' => $scope]);
        $this->doTest($expected, $input);
    }

    public function provideFixWithNamespaceConfigurationCases(): array
    {
        return [
            [
                '<?php echo count([1]);',
            ],
            [
                '<?php
namespace space1 { ?>
<?php echo \count([2]) ?>
<?php }namespace {echo count([1]);}
',
                '<?php
namespace space1 { ?>
<?php echo count([2]) ?>
<?php }namespace {echo count([1]);}
',
            ],
            [
                '<?php
namespace Bar {
    echo \strLEN("in 1");
}

namespace {
    echo strlen("out 1");
}

namespace {
    echo strlen("out 2");
}

namespace Bar{
    echo \strlen("in 2");
}

namespace {
    echo strlen("out 3");
}
',
                '<?php
namespace Bar {
    echo strLEN("in 1");
}

namespace {
    echo strlen("out 1");
}

namespace {
    echo strlen("out 2");
}

namespace Bar{
    echo strlen("in 2");
}

namespace {
    echo strlen("out 3");
}
',
            ],
            [
                '<?php
namespace space11 ?>

    <?php
echo \strlen(__NAMESPACE__);
namespace space2;
echo \strlen(__NAMESPACE__);
',
                '<?php
namespace space11 ?>

    <?php
echo strlen(__NAMESPACE__);
namespace space2;
echo strlen(__NAMESPACE__);
',
            ],
            [
                '<?php namespace PhpCsFixer\Tests\Fixer\Casing;\count([1]);',
                '<?php namespace PhpCsFixer\Tests\Fixer\Casing;count([1]);',
            ],
            [
                '<?php
namespace Space12;

echo \count([1]);

namespace Space2;

echo \count([1]);
?>
',
                '<?php
namespace Space12;

echo count([1]);

namespace Space2;

echo count([1]);
?>
',
            ],
            [
                '<?php namespace {echo strlen("out 2");}',
            ],
            [
                '<?php
namespace space13 {
    echo \strlen("in 1");
}

namespace space2 {
    echo \strlen("in 2");
}

namespace { // global
    echo strlen("global 1");
}
',
                '<?php
namespace space13 {
    echo strlen("in 1");
}

namespace space2 {
    echo strlen("in 2");
}

namespace { // global
    echo strlen("global 1");
}
',
            ],
            [
                '<?php
namespace space1 {
    echo \count([1]);
}
namespace {
    echo \count([1]);
}
',
                '<?php
namespace space1 {
    echo count([1]);
}
namespace {
    echo count([1]);
}
',
                'all',
            ],
        ];
    }

    /**
     * @dataProvider provideFixWithConfiguredIncludeCases
     */
    public function testFixWithConfiguredInclude(string $expected, ?string $input = null, array $configuration = []): void
    {
        $this->fixer->configure($configuration);

        $this->doTest($expected, $input);
    }

    public function provideFixWithConfiguredIncludeCases(): \Generator
    {
        yield from [
            'include set + 1, exclude 1' => [
                '<?php
                    echo \count([1]);
                    \some_other($a, 3);
                    echo strlen($a);
                    not_me();
                ',
                '<?php
                    echo count([1]);
                    some_other($a, 3);
                    echo strlen($a);
                    not_me();
                ',
                [
                    'include' => [NativeFunctionInvocationFixer::SET_INTERNAL, 'some_other'],
                    'exclude' => ['strlen'],
                ],
            ],
            'include @all' => [
                '<?php
                    echo \count([1]);
                    \some_other($a, 3);
                    echo \strlen($a);
                    \me_as_well();
                ',
                '<?php
                    echo count([1]);
                    some_other($a, 3);
                    echo strlen($a);
                    me_as_well();
                ',
                [
                    'include' => [NativeFunctionInvocationFixer::SET_ALL],
                ],
            ],
            'include @compiler_optimized' => [
                '<?php
                    // do not fix
                    $a = strrev($a);
                    $a .= str_repeat($a, 4);
                    $b = already_prefixed_function();
                    // fix
                    $c = \get_class($d);
                    $e = \intval($f);
                ',
                '<?php
                    // do not fix
                    $a = strrev($a);
                    $a .= str_repeat($a, 4);
                    $b = \already_prefixed_function();
                    // fix
                    $c = get_class($d);
                    $e = intval($f);
                ',
                [
                    'include' => [NativeFunctionInvocationFixer::SET_COMPILER_OPTIMIZED],
                ],
            ],
            [
                '<?php class Foo {
                        public function & strlen($name) {
                        }
                    }
                ',
            ],
            'scope namespaced and strict enabled' => [
                '<?php
                    $a = not_compiler_optimized_function();
                    $b = intval($c);
                ',
                '<?php
                    $a = \not_compiler_optimized_function();
                    $b = \intval($c);
                ',
                [
                    'scope' => 'namespaced',
                    'strict' => true,
                ],
            ],
            [
                '<?php
                    use function foo\json_decode;
                    json_decode($base);
                ',
                null,
                [
                    'include' => [NativeFunctionInvocationFixer::SET_ALL],
                ],
            ],
        ];

        if (\PHP_VERSION_ID < 80000) {
            yield 'include @compiler_optimized with strict enabled' => [
                '<?php
                        $a = not_compiler_optimized_function();
                        $b =  not_compiler_optimized_function();
                        $c = \intval($d);
                    ',
                '<?php
                        $a = \not_compiler_optimized_function();
                        $b = \ not_compiler_optimized_function();
                        $c = intval($d);
                    ',
                [
                    'include' => [NativeFunctionInvocationFixer::SET_COMPILER_OPTIMIZED],
                    'strict' => true,
                ],
            ];
        }
    }

    /**
     * @requires PHP 7.3
     */
    public function testFix73(): void
    {
        $this->doTest(
            '<?php $name = \get_class($foo, );',
            '<?php $name = get_class($foo, );'
        );
    }

    /**
     * @requires PHP <8.0
     */
    public function testFixPrePHP80(): void
    {
        $this->doTest(
            '<?php
echo \/**/strlen($a);
echo \ strlen($a);
echo \#
#
strlen($a);
echo \strlen($a);
',
            '<?php
echo \/**/strlen($a);
echo \ strlen($a);
echo \#
#
strlen($a);
echo strlen($a);
'
        );
    }

    /**
     * @dataProvider provideFix80Cases
     * @requires PHP 8.0
     */
    public function testFix80(string $expected, ?string $input = null, array $config = []): void
    {
        $this->fixer->configure($config);
        $this->doTest($expected, $input);
    }

    public function provideFix80Cases(): \Generator
    {
        yield 'attribute and strict' => [
            '<?php
                #[\Attribute(\Attribute::TARGET_CLASS)]
                class Foo {}
            ',
            null,
            ['strict' => true],
        ];

        yield 'null safe operator' => ['<?php $x?->count();'];

        yield 'multiple function-calls-like in attribute' => [
            '<?php
                #[Foo(), Bar(), Baz()]
                class Foo {}
            ',
            null,
            ['include' => ['@all']],
        ];
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>deep-insight</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-flat.min.css" rel="stylesheet">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          Toggle navigation

        </button>
        deep-insight

Flow Graph (current)

About

      Packet Count : 0


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

package com.google.sample.beaconservice;

import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;

import com.google.android.gms.maps.model.LatLng;

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

/**
 * A simple struct representation of a Beacon object. Supports basic parsing and serialization
 * to and from JSONObject.
 */
public class Beacon implements Parcelable {
  // These constants are in the Proximity Service Status enum:
  static final String STATUS_UNSPECIFIED = "STATUS_UNSPECIFIED";
  static final String STATUS_ACTIVE = "ACTIVE";
  static final String STATUS_INACTIVE = "INACTIVE";
  static final String STATUS_DECOMMISSIONED = "DECOMMISSIONED";
  static final String STABILITY_UNSPECIFIED = "STABILITY_UNSPECIFIED";

  // These constants are convenience for this app:
  static final String UNREGISTERED = "UNREGISTERED";
  static final String NOT_AUTHORIZED = "NOT_AUTHORIZED";

  String type;
  byte[] id;
  String status;
  String placeId;
  Double latitude;
  Double longitude;
  String expectedStability;
  String description;

  // This isn't really a beacon property, but it's useful to have it here so we can sort
  // the list of beacons during scanning so the closest and/or strongest is listed first.
  // It doesn't need to be persisted via the parcelable.
  int rssi;

  public Beacon(String type, byte[] id, String status, int rssi) {
    this.type = type;
    this.id = id;
    this.status = status;
    this.placeId = null;
    this.latitude = null;
    this.longitude = null;
    this.expectedStability = null;
    this.description = null;
    this.rssi = rssi;
  }

  public Beacon(JSONObject response) {
    try {
      JSONObject json = response.getJSONObject("advertisedId");
      type = json.getString("type");
      id = Utils.base64Decode(json.getString("id"));
    } catch (JSONException e) {
      // NOP
    }

    try {
      status = response.getString("status");
    } catch (JSONException e) {
      status = STATUS_UNSPECIFIED;
    }

    try {
      placeId = response.getString("placeId");
    } catch (JSONException e) {
      // NOP
    }

    try {
      JSONObject latLngJson = response.getJSONObject("latLng");
      latitude = latLngJson.getDouble("latitude");
      longitude = latLngJson.getDouble("longitude");
    } catch (JSONException e) {
      latitude = null;
      longitude = null;
    }

    try {
      expectedStability = response.getString("expectedStability");
    } catch (JSONException e) {
      // NOP
    }

    try {
      description = response.getString("description");
    } catch (JSONException e) {
      // NOP
    }

  }

  public JSONObject toJson() throws JSONException {
    JSONObject json = new JSONObject();
    JSONObject advertisedId = new JSONObject()
        .put("type", type)
        .put("id", Utils.base64Encode(id));
    json.put("advertisedId", advertisedId);
    if (!status.equals(STATUS_UNSPECIFIED)) {
      json.put("status", status);
    }
    if (placeId != null) {
      json.put("placeId", placeId);
    }
    if (latitude != null && longitude != null) {
      JSONObject latLng = new JSONObject();
      latLng.put("latitude", latitude);
      latLng.put("longitude", longitude);
      json.put("latLng", latLng);
    }
    if (expectedStability != null && !expectedStability.equals(STABILITY_UNSPECIFIED)) {
      json.put("expectedStability", expectedStability);
    }
    if (description != null) {
      json.put("description", description);
    }
    // TODO: beacon properties
    return json;
  }

  public String getHexId() {
    return Utils.toHexString(id);
  }

  /**
   * The beaconName is formatted as "beacons/%d!%s" where %d is an integer representing the
   * beacon ID type. For Eddystone this is 3. The %s is the base16 (hex) ASCII for the ID bytes.
   */
  public String getBeaconName() {
    return String.format("beacons/3!%s", getHexId());
  }

  @Nullable
  public LatLng getLatLng() {
    if (latitude == null || longitude == null) {
      return null;
    }
    return new LatLng(latitude, longitude);
  }

  @Override
  public int describeContents() {
    return 0;
  }

  private Beacon(Parcel source) {
    type = source.readString();
    int len = source.readInt();
    id = new byte[len];
    source.readByteArray(id);
    status = source.readString();
    if (source.readInt() == 1) {
      placeId = source.readString();
    }
    if (source.readInt() == 1) {
      latitude = source.readDouble();
    }
    if (source.readInt() == 1) {
      longitude = source.readDouble();
    }
    if (source.readInt() == 1) {
      expectedStability = source.readString();
    }
    if (source.readInt() == 1) {
      description = source.readString();
    }
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(type);
    dest.writeByteArray(id);
    dest.writeString(status);
    if (placeId != null) {
      dest.writeInt(1);
      dest.writeString(placeId);
    } else {
      dest.writeInt(0);
    }
    if (latitude != null) {
      dest.writeInt(1);
      dest.writeDouble(latitude);
    } else {
      dest.writeInt(0);
    }
    if (longitude != null) {
      dest.writeInt(1);
      dest.writeDouble(longitude);
    } else {
      dest.writeInt(0);
    }
    if (expectedStability != null ) {
      dest.writeInt(1);
      dest.writeString(expectedStability);
    } else {
      dest.writeInt(0);
    }
    if (description != null) {
      dest.writeInt(1);
      dest.writeString(description);
    } else {
      dest.writeInt(0);
    }
  }

  public static final Parcelable.Creator<Beacon> CREATOR = new Parcelable.Creator<Beacon>() {

    @Override
    public Beacon createFromParcel(Parcel source) {
      return new Beacon(source);
    }

    @Override
    public Beacon[] newArray(int size) {
      return new Beacon[size];
    }
  };

}


text:
<?php

namespace Phervice;

class Container {

	/**
	 * array of Service instances
	 *
	 * @var array
	 */
	protected $instances = array();

	/**
	 * mapping of aliases to service names
	 *
	 * @var array
	 */
	protected $aliases = array();

	/**
	 * mapping of regex queries to thier observer service names
	 *
	 * @var array
	 */
	protected $observers = array();

	/**
	 * mapping of service names to thier observer Service instances
	 *
	 * @var array
	 */
	protected $serviceObservers = array();

	/**
	 *
	 * @var bool
	 */
	protected $modified = false;

	/**
	 * creates new Container instance
	 *
	 * @param array $config
	 * @param \Phervice\Cache $cache
	 */
	public function __construct(array $config=array()) {

		if (isset($config['aliases']) && is_array($config['aliases'])) {
			$this->aliases = $config['aliases'];
		}

		if (isset($config['observers']) && is_array($config['observers'])) {
			$this->observers = $config['observers'];
		}
	}

	/**
	 *
	 * @return bool
	 */
	public function getModified() {
		return $this->modified;
	}

	/**
	 * inits a service by name, happens automatically first time a service is used
	 *
	 * @param string $serviceName - name of service to init
	 */
	public function init($serviceName) {
		$this->get($serviceName);
	}

	/**
	 * invokes a service, first arg is the serviceName, additional args are passed to the service
	 *
	 * @param string $serviceName
	 * @return mixed - result of the service invocation
	 */
	public function exec($serviceName) {
		$args = func_get_args();
		array_shift($args);
		return $this->execArgs($serviceName, $args);
	}

	/**
	 * invokes any observers of the passed service name, additional args after the first are passed
	 * to the observers
	 *
	 * @param type $serviceName
	 */
	public function broadcast($serviceName) {
		$args = func_get_args();
		array_shift($args);
		$this->broadcastArgs($serviceName, $args);
	}

	/**
	 * invokes the named sesrvice
	 *
	 * @param string $serviceName
	 * @param array $args
	 * @return mixed - result of the service invocation
	 */
	public function execArgs($serviceName, array $args) {

		$service = $this->get($serviceName);
		$observers = $this->getObservers($serviceName);

		if (count($observers) === 0) {
			return $service->handle($args);

		} else {
			return Chain::invoke($serviceName, $observers, $args, $service);
		}
	}

	/**
	 *
	 * @param string $serviceName
	 * @param array $args
	 */
	public function broadcastArgs($serviceName, array $args) {
		$observers = $this->getObservers($serviceName);
		return Chain::invoke($serviceName, $observers, $args);
	}

	/**
	 *
	 *
	 * @param string $serviceName
	 * @return array
	 */
	protected function getObservers($serviceName) {

		if (isset($this->serviceObservers[$serviceName]) === false) {

			$this->modified = true;

			$observerMap = array();
			foreach($this->observers as $query => $observers) {
				if (preg_match($query, $serviceName)) {
					$observerMap += $observers;
				}
			}
			$observerMap = array_unique($observerMap);

			$observers = array();
			foreach($observerMap as $observerName) {
				$observers[] = $this->get($observerName);
			}

			$this->serviceObservers[$serviceName] = $observers;
		}

		return $this->serviceObservers[$serviceName];
	}

	/**
	 *
	 *
	 * @param string $serviceName
	 * @return Service
	 */
	protected function get($serviceName) {

		if (isset($this->aliases[$serviceName])) {
			$serviceName = $this->aliases[$serviceName];
		}

		# if service exists return it now
		if (isset($this->instances[$serviceName])) {
			return $this->instances[$serviceName];
		}

		# resolve class name
		$segments = str_replace('.', ' ', $serviceName);
		$ucSegments = ucwords($segments);
		$className = str_replace(' ', '\\', $ucSegments);

		$this->modified = true;

		# if no class then create a new one
		if (isset($this->instances[$className]) === false) {
			$this->instances[$className] = new Service($className, $this);
		}

		# return instance and map to service name
		return $this->instances[$serviceName] = $this->instances[$className];
	}
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LordJZ.ObjectManagement;

namespace LordJZ.Collections.Proxies
{
    public sealed class ReadOnlyListProxy<T> : IReadOnlyList<T>, IObjectProxy<IReadOnlyList<T>>
    {
        readonly IReadOnlyList<T> m_list;

        public ReadOnlyListProxy(IReadOnlyList<T> list)
        {
            Contract.Requires(list != null);

            this.m_list = list;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return this.m_list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public int Count { get { return this.m_list.Count; } }

        public T this[int index]
        {
            get { return this.m_list[index]; }
        }

        object IObjectProxy.ProxifiedObject
        {
            get { return ProxifiedObject; }
        }

        public IReadOnlyList<T> ProxifiedObject { get { return this.m_list; } }
    }
}


text:
This is a simple example implementation of the Inverse Compositional[1] method
which is a variant on the Lucas-Kanade[2] algorithm for image registration.
The difference is that it keeps the Gauss-Newton approximation to the Hessian fixed across iterations.

For extra credit I've also thrown in a Huber[3] loss function to make it robust to outliers but have not really played much with it.
Set it to 1 for regular quadratic loss

But why is it called sim2-alignment?
Because it estimates the parameters for translation,
rotation and scale, i.e. a similarity transform in 2D

Dependencies:

This program depends on Eigen3, OpenCV and cmake (and optionally OpenMP).
Compilation instructions:

```sh
$ mkdir build && cd build
$ cmake ..
$ make
```
Running the program:

from the main directory:

```sh
./bin/align lena_src.png lena.png 150 50
./bin/align cameraman_src.png cameraman.png
./bin/align cat_src.png cat.png 160 160
```

The first and third images are more challenging, but given the initialization (offset in rows and columns respectively) they converge.

##References:
 - [1] Baker, Simon, and Iain Matthews. "Lucas-kanade 20 years on: A unifying framework." International journal of computer vision 56.3 (2004): 221-255.

 - [2] Lucas, Bruce D., and Takeo Kanade. "An iterative image registration technique with an application to stereo vision." IJCAI. Vol. 81. No. 1. 1981.

 - [3] Huber, Peter J. "Robust estimation of a location parameter." The Annals of Mathematical Statistics 35.1 (1964): 73-101.

 ##(c) Daniel Ricão Canelhas


text:
#region License

#endregion

using System;
using System.IO;
using System.Numerics;

namespace Revise.Files.ZMO.Channels {
    /// <summary>
    /// Represents a rotation channel.
    /// </summary>
    public class RotationChannel : MotionChannel {
        #region Properties

        /// <summary>
        /// Gets the channel type.
        /// </summary>
        public override ChannelType Type {
            get {
                return ChannelType.Rotation;
            }
        }

        /// <summary>
        /// Sets the frame count.
        /// </summary>
        internal override int FrameCount {
            set {
                Array.Resize<Quaternion>(ref frames, value);
            }
        }

        /// <summary>
        /// Gets the frames.
        /// </summary>
        public Quaternion[] Frames {
            get {
                return frames;
            }
        }

        #endregion

        private Quaternion[] frames;

        /// <summary>
        /// Initializes a new instance of the <see cref="RotationChannel"/> class.
        /// </summary>
        public RotationChannel() {
            frames = new Quaternion[0];
        }

        /// <summary>
        /// Reads a channel frame from the underlying stream.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="frame">The frame to read.</param>
        public override void ReadFrame(BinaryReader reader, int frame) {
            frames[frame] = reader.ReadQuaternion(true);
        }

        /// <summary>
        /// Writes the specified channel frame to the underlying stream.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="frame">The frame to write.</param>
        public override void WriteFrame(BinaryWriter writer, int frame) {
            writer.Write(frames[frame], true);
        }
    }
}


text:
============
Sorted Loop2
============

Question
--------

Sorted Loop comparision with the previous program.

Solution
--------

.. literalinclude:: ../../languages/python/design_sorted_loop2.py
   :language: python
   :tab-width: 4

.. runcode:: ../../languages/python/design_sorted_loop2.py
   :language: python
   :codesite: ideone

Explanation
===========

.. git_changelog::

.. seealso::

   * :python-suggest-improve:`design_sorted_loop2.py`
   * :python-better-explain:`design_sorted_loop2.rst`


text:
{% extends '_base.html' %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}

Create New Event

  <form class="form" role="form" method="post" action="">

    {{ form.csrf_token }}
    {{ form.hidden_tag() }}
    {{ wtf.form_errors(form, hiddens="only") }}

      {{ wtf.form_field(form.name) }}
      {{ wtf.form_field(form.description) }}
      {{ wtf.form_field(form.start_date) }}
      {{ wtf.form_field(form.start_time) }}
      {{ wtf.form_field(form.end_date) }}
      {{ wtf.form_field(form.end_time) }}

      <button class="btn btn-success" type="submit">Create Event</button>

  </form>

{% endblock content %}


text:
import os
import sys
import argparse
from datetime import timedelta

import numpy as np
import matplotlib.pyplot as plt

from pygeotools.lib import iolib, malib, geolib, warplib, timelib

def make_plot(m, fig_fn, label):
    f, ax = plt.subplots(figsize=(7,7))
    #plt.title('%s to %s' % (t1.strftime('%Y-%m-%d'), t2.strftime('%Y-%m-%d')))
    perc = malib.calcperc(m, (2,98))
    cmap = 'inferno'
    imgplot = ax.imshow(m, cmap=cmap)
    imgplot.set_clim(*perc)
    imgplot.axes.get_xaxis().set_visible(False)
    imgplot.axes.get_yaxis().set_visible(False)
    imgplot.axes.patch.set_facecolor('0.5')
    cb = plt.colorbar(imgplot, orientation='vertical', extend='both', shrink=0.5)
    cb.set_label(label)
    return f, ax

#Streamline plot
def streamline_plt(u,v,bg=None):
    """
    Generate a stremline plot for velocity field
    This needs further development and testing
    """
    dx = 1
    m = np.ma.sqrt(u*u + v*v)
    x,y = np.meshgrid(np.arange(0,u.shape[1],dx),np.arange(0,u.shape[0],dx))
    if bg is None:
        bg = m
    plt.imshow(bg)
    #plt.streamplot(x,y,u,v,color='k', linewidth=5*m/m.max())
    plt.streamplot(x,y,u,v,color='k')
    plt.show()

def compute_stride(a):
    return stride

def plotvec(h, v):
    #Probably want to smooth h and v here, or at least filter outliers
    #Interpolation or hole filling would also help with lots of nodata holes
    #Compute stats within window centered on X and Y
    nvec = np.array([40,40], dtype=np.float)
    stride = np.round(min(h.shape/nvec)).astype('int')
    X,Y = np.meshgrid(np.arange(0,h.shape[1],stride),np.arange(0,h.shape[0],stride))
    h_sub = h[::stride,::stride]
    v_sub = v[::stride,::stride]
    norm = False
    if norm:
        m_sub = np.ma.sqrt(h_sub**2+v_sub**2)
        h_sub /= m_sub
        v_sub /= m_sub
    Q = plt.quiver(X,Y,h_sub,v_sub,pivot='middle',color='white')
    #Add quiver key
    #scale = float(Q.scale)
    #lbl = str(np.round(Q.scale).astype(int)) + r'$\frac{m}{s}$'
    #lbl = '%i m/s' % np.around(scale, decimals=0).astype(int)
    #qk = plt.quiverkey(Q, 0.05, 0.05, 1, lbl, labelpos='N', fontproperties={'weight':'bold'})

def getparser():
    parser = argparse.ArgumentParser(description="Convert ASP disparity map to velocity map(s)")
    parser.add_argument('-dt', type=str, choices=['yr','day'], default='yr', help='Time increment (default: %(default)s)')
    parser.add_argument('-remove_offsets', action='store_true', help='Remove median offset from stable control surfaces, requires demcoreg or input mask')
    parser.add_argument('-mask_fn', type=str, default=None, help='Provide existing raster or vector mask for offset correction. If None, will automatically determine valid control surfaces (excluding glaciers, vegetation, etc.). This should work for any supported GDAL/OGR formats. For raster input, expects integer pixel values of 1 for valid control surfaces, 0 for surfaces to ignore during offset determination.')
    parser.add_argument('-plot', action='store_true', help='Generate plot of velocity magnitude with vectors overlaid')
    parser.add_argument('disp_fn', type=str, help='Disparity map filename (e.g., *-RD.tif, *-F.tif)')
    return parser

def main():
    parser = getparser()
    args = parser.parse_args()

    t_unit = args.dt
    plot = args.plot
    remove_offsets = args.remove_offsets
    mask_fn = args.mask_fn
    if mask_fn is not None:
        remove_offsets = True

    #Input is 3-band disparity map, extract bands directly
    src_fn = args.disp_fn
    if not iolib.fn_check(src_fn):
        sys.exit("Unable to locate input file: %s" % src_fn)

    src_ds = iolib.fn_getds(src_fn)
    if src_ds.RasterCount != 3:
        sys.exit("Input file must be ASP disparity map (3 bands: x, y, mask)")
    #Extract pixel resolution
    h_res, v_res = geolib.get_res(src_ds)

    #Horizontal scale factor
    #If running on disparity_view output (gdal_translate -outsize 5% 5% F.tif F_5.tif)
    #h_res /= 20
    #v_res /= 20

    #Load horizontal and vertical disparities
    h = iolib.ds_getma(src_ds, bnum=1)
    v = iolib.ds_getma(src_ds, bnum=2)

    #ASP output has northward motion as negative values in band 2
    v *= -1

    t1, t2 = timelib.fn_getdatetime_list(src_fn)
    dt = t2 - t1
    #Default t_factor is in 1/years
    t_factor = timelib.get_t_factor(t1,t2)

    #Input timestamp arrays if inputs are mosaics
    if False:
        t1_fn = ''
        t2_fn = ''
        if os.path.exists(t1_fn) and os.path.exists(t2_fn):
            t_factor = timelib.get_t_factor_fn(t1_fn, t2_fn)
        if t_factor is None:
            sys.exit("Unable to determine input timestamps")

    if t_unit == 'day':
        t_factor *= 365.25

    print("Input dates:")
    print(t1)
    print(t2)
    print(dt)
    print(t_factor, t_unit)

    #Scale values for polar stereographic distortion
    srs = geolib.get_ds_srs(src_ds)
    proj_scale_factor = 1.0
    #Want to scale to get correct distances for polar sterographic
    if srs.IsSame(geolib.nps_srs) or srs.IsSame(geolib.sps_srs):
        proj_scale_factor = geolib.scale_ps_ds(src_ds)

    #Convert disparity values in pixels to m/t_unit
    h_myr = h*h_res*proj_scale_factor/t_factor
    h = None
    v_myr = v*v_res*proj_scale_factor/t_factor
    v = None

    #Velocity Magnitude
    m = np.ma.sqrt(h_myr**2+v_myr**2)
    print("Velocity Magnitude stats")
    malib.print_stats(m)

    #Remove x and y offsets over control surfaces
    offset_str = ''
    if remove_offsets:
        if mask_fn is None:
            from demcoreg.dem_mask import get_mask
            print("\nUsing demcoreg to prepare mask of stable control surfaces\n")
            #TODO: Accept mask_list as in demcoreg
            #mask_list = args.mask_list
            # for now keep it simple, limit to non-glacier surfaces
            mask_list = ['glaciers',]
            mask = get_mask(src_ds, mask_list=mask_list, dem_fn=src_fn)
        else:
            print("\nWarping input raster mask")
            #This can be from previous dem_mask.py run (e.g. *rockmask.tif)
            mask_ds = warplib.memwarp_multi_fn([mask_fn,], res=src_ds, extent=src_ds, t_srs=src_ds)[0]
            mask = iolib.ds_getma(mask_ds)
            #The default from ds_getma is a masked array, so need to isolate boolean mask
            #Assume input is 0 for masked, 1 for unmasked (valid control surface)
            mask = mask.filled().astype('bool')
            #This should work, as the *rockmask.py is 1 for unmasked, 0 for masked, with ndv=0
            #mask = np.ma.getmaskarray(mask)
            #Vector mask - untested
            if os.path.splitext(mask_fn)[1] == 'shp':
                mask = geolib.shp2array(mask_fn, src_ds)

        print("\nRemoving median x and y offset over static control surfaces")
        h_myr_count = h_myr.count()
        h_myr_static_count = np.ma.array(h_myr,mask=mask).count()
        h_myr_mad,h_myr_med = malib.mad(np.ma.array(h_myr,mask=mask),return_med=True)
        v_myr_mad,v_myr_med = malib.mad(np.ma.array(v_myr,mask=mask),return_med=True)

        print("Static pixel count: %i (%0.1f%%)" % (h_myr_static_count, 100*float(h_myr_static_count)/h_myr_count))
        print("median (+/-NMAD)")
        print("x velocity offset: %0.2f (+/-%0.2f) m/%s" % (h_myr_med, h_myr_mad, t_unit))
        print("y velocity offset: %0.2f (+/-%0.2f) m/%s" % (v_myr_med, v_myr_mad, t_unit))
        h_myr -= h_myr_med
        v_myr -= v_myr_med
        offset_str = '_offsetcorr_h%0.2f_v%0.2f' % (h_myr_med, v_myr_med)
        #Velocity Magnitude
        m = np.ma.sqrt(h_myr**2+v_myr**2)
        print("Velocity Magnitude stats after correction")
        malib.print_stats(m)

    if plot:
        fig_fn = os.path.splitext(src_fn)[0]+'.png'
        label='Velocity (m/%s)' % t_unit
        f, ax = make_plot(m, fig_fn, label)
        plotvec(h_myr, v_myr)
        plt.tight_layout()
        plt.savefig(fig_fn, dpi=300, bbox_inches='tight', pad_inches=0, edgecolor='none')

    print("Writing out files")
    gt = src_ds.GetGeoTransform()
    proj = src_ds.GetProjection()
    dst_fn = os.path.splitext(src_fn)[0]+'_vm%s.tif' % offset_str
    iolib.writeGTiff(m, dst_fn, create=True, gt=gt, proj=proj)
    dst_fn = os.path.splitext(src_fn)[0]+'_vx%s.tif' % offset_str
    iolib.writeGTiff(h_myr, dst_fn, create=True, gt=gt, proj=proj)
    dst_fn = os.path.splitext(src_fn)[0]+'_vy%s.tif' % offset_str
    iolib.writeGTiff(v_myr, dst_fn, create=True, gt=gt, proj=proj)
    src_ds = None

if __name__ == "__main__":
    main()


text:
package com.adobe.acs.commons.forms.impl;

import com.adobe.acs.commons.forms.FormsRouter;
import com.adobe.acs.commons.util.PathInfoUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

@Component(label = "ACS AEM Commons - Forms Router",
        description = "Provides functionality for routing ACS AEM Commons FORM Requests through AEM.",
        policy = ConfigurationPolicy.REQUIRE,
        metatype = true)
@Service
public class FormsRouterImpl implements FormsRouter {
    private static final Logger log = LoggerFactory.getLogger(FormsRouterImpl.class);

    private static final String DEFAULT_SUFFIX = "/submit/form";

    private String suffix = DEFAULT_SUFFIX;

    @Property(label = "Forms Suffix",
            description = "HTTP Request Suffix used to identify ACS AEM Commons Forms POST Requests and route them "
                    + "appropriately. [ Default: /submit/form ]",
            value = DEFAULT_SUFFIX)
    private static final String PROP_SUFFIX = "suffix";

    /**
     * Gets the Form Selector for the form POST request.
     *
     * @param slingRequest
     * @return
     */
    @Override
    public final String getFormSelector(final SlingHttpServletRequest slingRequest) {
        final String requestSuffix = slingRequest.getRequestPathInfo().getSuffix();
        if (StringUtils.equals(requestSuffix, this.getSuffix())
                || !StringUtils.startsWith(requestSuffix, this.getSuffix() + "/")) {
            return null;
        }

        final int segments = StringUtils.split(this.getSuffix(), '/').length;
        if (segments < 1) {
            return null;
        }

        final String formSelector = PathInfoUtil.getSuffixSegment(slingRequest, segments);
        return StringUtils.stripToNull(formSelector);
    }

    @Override
    public final String getSuffix() {
        return this.suffix;
    }

    @Override
    public final boolean hasValidSuffix(final SlingHttpServletRequest slingRequest) {
        final String requestSuffix = slingRequest.getRequestPathInfo().getSuffix();
        if (StringUtils.equals(requestSuffix, this.getSuffix())
                || StringUtils.startsWith(requestSuffix, this.getSuffix() + "/")) {
            return true;
        }

        return false;
    }

    @Activate
    protected final void activate(final Map<String, String> properties) {
        this.suffix = PropertiesUtil.toString(properties.get(PROP_SUFFIX), DEFAULT_SUFFIX);
        if (StringUtils.isBlank(this.suffix)) {
            // No whitespace please
            this.suffix = DEFAULT_SUFFIX;
        }

        log.debug("Forms Router suffix: {}", this.suffix);
    }
}


text:
package com.superSaller.beans.outsideSupportSys.Impl.test;

import static org.junit.Assert.assertEquals;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.superSaller.beans.outsideSupportSys.Impl.GoodsSupportImpl;
import com.superSaller.beans.outsideSupportSys.entities.Good;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:dispatcherServlet-servlet.xml" })
public class GoodsSupportImplTest extends AbstractJUnit4SpringContextTests {
	@Resource(name = "goodsSupport")
	private GoodsSupportImpl goodsSupport;

	@Test
	public void testGetGoodMethod() {
		Good good = goodsSupport.getGood("2119008");
		assertEquals("2119008", good.getGoodID());
		assertEquals("味全活性乳酸菌饮品(芦荟味)", good.getGoodName());
	}
}


text:
require 'rails_helper'

RSpec.describe "email_subscriptions/index", type: :view do
  before(:each) do
    assign(:email_subscriptions, [
      EmailSubscription.create!(),
      EmailSubscription.create!()
    ])
  end

  it "renders a list of email_subscriptions" do
    render
  end
end


text:
package com.ontraport.app.pages;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

import com.ontraport.app.tools.AbstractPage;

public class UltraCart_View extends AbstractPage
{

    protected String   url = "/#!/ultracart/view";

    @FindBy(how = How.XPATH, using = "//body")
    private WebElement body;

    public UltraCart_View sample () throws Exception
    {
        return PageFactory.initElements(driver, UltraCart_View.class);
    }

}


text:
'''
Author: Wenchang Yang (yang.wenchang@uci.edu)
'''

from .accessor import LearnAccessor


text:
describe('App', () => {

  beforeEach(() => {
    // change hash depending on router LocationStrategy
    browser.get('/#/home');
  });

  it('should have `your content here` x-large', () => {
    let subject = element(by.css('[x-large]')).getText();
    let result  = 'Your Content Here';
    expect(subject).toEqual(result);
  });

});