text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Reloading Source Code — mod_wsgi 4.5.22 documentation</title>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="../genindex.html"/>
        <link rel="search" title="Search" href="../search.html"/>
    <link rel="top" title="mod_wsgi 4.5.22 documentation" href="../index.html"/>
        <link rel="up" title="User Guides" href="../user-guides.html"/>
        <link rel="next" title="Virtual Environments" href="virtual-environments.html"/>
        <link rel="prev" title="Processes And Threading" href="processes-and-threading.html"/>

             mod_wsgi

                4.5

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Project Status

Security Issues

Getting Started

Requirements

Installation

Troubleshooting

User Guides

Quick Installation Guide

Installation On MacOS X

Quick Configuration Guide

Configuration Guidelines

Installation Issues

Configuration Issues

Application Issues

Frequently Asked Questions

Checking Your Installation

Debugging Techniques

Processes And Threading

Reloading Source Code

Embedded Mode Vs Daemon Mode

Reloading In Embedded Mode

Restarting Apache Processes

Reloading In Daemon Mode

Restarting Daemon Processes

Monitoring For Code Changes

Restarting Windows Apache

Virtual Environments

Access Control Mechanisms

File Wrapper Extension

Registering Cleanup Code

Assorted Tips And Tricks

Issues With Pickle Module

Issues With Expat Library

Configuration

Finding Help

Reporting Bugs

Contributing

Source Code

Release Notes

          mod_wsgi

Docs »

User Guides »

Reloading Source Code

             View page source

Reloading Source Code¶

This document contains information about mechanisms available in mod_wsgi
for automatic reloading of source code when an application is changed and
any issues related to those mechanisms.

Embedded Mode Vs Daemon Mode¶

What is achievable in the way of automatic source code reloading depends on
which mode your WSGI application is running.

If your WSGI application is running in embedded mode then what happens when
you make code changes is largely dictated by how Apache works, as it
controls the processes handling requests. In general, if using embedded
mode you will have no choice but to manually restart Apache in order for code
changes to be used.

If using daemon mode, because mod_wsgi manages directly the processes
handling requests and in which your WSGI application runs, there is more
avenue for performing automatic source code reloading.

As a consequence, it is important to understand what mode your WSGI
application is running in.

If you are running on Windows, are using Apache 1.3, or have not used
WSGIDaemonProcess/WSGIProcessGroup directives to delegate your WSGI
application to a mod_wsgi daemon mode process, then you will be using
embedded mode.

If you are not sure whether you are using embedded mode or daemon mode,
then substitute your WSGI application entry point with:

def application(environ, start_response):
    status = '200 OK'

    if not environ['mod_wsgi.process_group']:
      output = u'EMBEDDED MODE'
    else:
      output = u'DAEMON MODE'

    response_headers = [('Content-Type', 'text/plain'),
                        ('Content-Length', str(len(output)))]

    start_response(status, response_headers)

    return [output.encode('UTF-8')]

If your WSGI application is running in embedded mode, this will output to
the browser 'EMBEDDED MODE'. If your WSGI application is running in daemon
mode, this will output to the browser 'DAEMON MODE'.

Reloading In Embedded Mode¶

However you have configured Apache to mount your WSGI application, you will
have a script file which contains the entry point for the WSGI application.
This script file is not treated exactly like a normal Python module and
need not even use a '.py' extension. It is even preferred that a '.py'
extension not be used for reasons described below.

For embedded mode, one of the properties of the script file is that by
default it will be reloaded whenever the file is changed. The primary
intent with the file being reloaded is to provide a second chance at
getting any configuration in it and the mapping to the application correct.
If the script weren't reloaded in this way, you would need to restart
Apache even for a trivial change to the script file.

Do note though that this script reloading mechanism is not intended as a
general purpose code reloading mechanism. Only the script file itself is
reloaded, no other Python modules are reloaded. This means that if modifying
normal Python code files which are used by your WSGI application, you will
need to trigger a restart of Apache. For example, if you are using Django
in embedded mode and needed to change your 'settings.py' file, you would
still need to restart Apache.

That only the script file and not the whole process is reloaded also has a
number of implications and imposes certain restrictions on what code in the
script file can do or how it should be implemented.

The first issue is that when the script file is imported, if the code makes
modifications to sys.path or other global data structures and the
changes are additive, checks should first be made to ensure that the change
has not already been made, else duplicate data will be added every time the
script file is reloaded.

This means that when updating sys.path, instead of using:

import sys
sys.path.append('/usr/local/wsgi/modules')

the more correct way would be to use:

import sys
path = '/usr/local/wsgi/modules'
if path not in sys.path:
    sys.path.append(path)

This will ensure that the path doesn't get added multiple times.

Even where the script file is named so as to have a '.py' extension, that
the script file is not treated like a normal module means that you should
never try to import the file from another code file using the 'import'
statement or any other import mechanism. The easiest way to avoid this is
not use the '.py' extension on script files or never place script files in
a directory which is located on the standard module search path, nor add
the directory containing the script into sys.path explicitly.

If an attempt is made to import the script file as a module the result will
be that it will be loaded a second time as an independent module. This is
because script files are loaded under a module name which is keyed to the
full absolute path for the script file and not just the basename of the
file. Importing the script file directly and accessing it will therefore
not result in the same data being accessed as exists in the script file
when loaded.

Because the script file is not treated like a normal Python module also has
implications when it comes to using the "pickle" module in conjunction
with objects contained within the script file.

In practice what this means is that neither function objects, class objects
or instances of classes which are defined in the script file should be
stored using the "pickle" module.

The technical reasons for the limitations on the use of the "pickle" module
in conjunction with objects defined in the script file are further
discussed in the document Issues With Pickle Module.

The act of reloading script files also means that any data previously held
by the module corresponding to the script file will be deleted. If such
data constituted handles to database connections, and the connections are
not able to clean up themselves when deleted, it may result in resource
leakage.

One should therefore be cautious of what data is kept in a script file.
Preferably the script file should only act as a bridge to code and data
residing in a normal Python module imported from an entirely different
directory.

Restarting Apache Processes¶

As explained above, the only facility that mod_wsgi provides for reloading
source code files in embedded mode, is the reloading of just the script
file providing the entry point for your WSGI application.

If you don't have a choice but to use embedded mode and still desire some
measure of automatic source code reloading, one option available which
works for both Windows and UNIX systems is to force Apache to recycle the
Apache server child process that handles the request automatically after
the request has completed.

To enable this, you need to modify the value of the MaxRequestsPerChild
directive in the Apache configuration. Normally this would be set to a
value of '0', indicating that the process should never be restarted as a
result of the number of requests processed. To have it restart a process
after every request, set it to the value '1' instead:

MaxRequestsPerChild 1

Do note however that this will cause the process to be restarted after any
request. That is, the process will even be restarted if the request was for
a static file or a PHP application and wasn't even handled by your WSGI
application. The restart will also occur even if you have made no changes
to your code.

Because a restart happens regardless of the request type, using this method
is not recommended.

Because of how the Apache server child processes are monitored and restarts
handled, it is technically possible that this method will yield performance
which is worse than CGI scripts. For that reason you may even be better off
using a CGI/WSGI bridge to host your WSGI application. At least that way
the handling of other types of requests, such as for static files and PHP
applications will not be affected.

Reloading In Daemon Mode¶

If using mod_wsgi daemon mode, what happens when the script file is changed
is different to what happens in embedded mode. In daemon mode, if the
script file changed, rather than just the script file being reloaded, the
daemon process which contains the application will be shutdown and
restarted automatically.

Detection of the change in the script file will occur at the time of the
first request to arrive after the change has been made. The way that the
restart is performed does not affect the handling of the request, with it
still being processed once the daemon process has been restarted.

In the case of there being multiple daemon processes in the process group,
then a cascade effect will occur, with successive processes being restarted
until the request is again routed to one of the newly restarted processes.

In this way, restarting of a WSGI application when a change has been made
to the code is a simple matter of touching the script file if daemon mode
is being used. Any daemon processes will then automatically restart without
the need to restart the whole of Apache.

So, if you are using Django in daemon mode and needed to change your
'settings.py' file, once you have made the required change, also touch the
script file containing the WSGI application entry point. Having done that,
on the next request the process will be restarted and your Django
application reloaded.

Restarting Daemon Processes¶

If you are using daemon mode of mod_wsgi, restarting of processes can to a
degree also be controlled by a user, or by the WSGI application itself,
without restarting the whole of Apache.

To force a daemon process to be restarted, if you are using a single daemon
process with many threads for the application, then you can embed a page in
your application (password protected hopefully), that sends an appropriate
signal to itself.

This should only be done for daemon processes and not within the Apache
child processes, as sending such a signal within a child process may
interfere with the operation of Apache. That the code is executing within a
daemon process can be determined by checking the 'mod_wsgi.process_group'
variable in the WSGI environment passed to the application. The value will
be non empty if a daemon process:

if environ['mod_wsgi.process_group'] != '':
    import signal, os
    os.kill(os.getpid(), signal.SIGINT)

This will cause the daemon process your application is in to shutdown. The
Apache process supervisor will then automatically restart your process
ready for subsequent requests. On the restart it will pick up your new
code. This way you can control a reload from your application through some
special web page specifically for that purpose.

You can also send this signal from an external application, but a problem
there may be identifying which process to send the signal to. If you are
running the daemon process(es) as a distinct user/group to Apache and each
application is running as a different user then you could just look for the
Apache (httpd) processes owned by the user the application is running as,
as opposed to the Apache user, and send them all signals.

If the daemon process is running as the same user as Apache or there are
distinct applications running in different daemon processes but as the same
user, knowing which daemon processes to send the signal may be harder to
determine.

Either way, to make it easier to identify which processes belong to a
daemon process group, you can use the 'display-name' option to the
WSGIDaemonProcess to name the process. On many platforms, when this option
is used, that name will then appear in the output from the 'ps' command
and not the name of the actual Apache server binary.

Monitoring For Code Changes¶

The use of signals to restart a daemon process could also be employed in a
mechanism which automatically detects changes to any Python modules or
dependent files. This could be achieved by creating a thread at startup
which periodically looks to see if file timestamps have changed and trigger
a restart if they have.

Example code for such an automatic restart mechanism which is compatible
with how mod_wsgi works is shown below:

from __future__ import print_function

import os
import sys
import time
import signal
import threading
import atexit

try:
    import Queue as queue
except ImportError:
    import queue

_interval = 1.0
_times = {}
_files = []

_running = False
_queue = queue.Queue()
_lock = threading.Lock()

def _restart(path):
    _queue.put(True)
    prefix = 'monitor (pid=%d):' % os.getpid()
    print('%s Change detected to \'%s\'.' % (prefix, path), file=sys.stderr)
    print('%s Triggering process restart.' % prefix, file=sys.stderr)
    os.kill(os.getpid(), signal.SIGINT)

def _modified(path):
    try:
        # If path doesn't denote a file and were previously
        # tracking it, then it has been removed or the file type
        # has changed so force a restart. If not previously
        # tracking the file then we can ignore it as probably
        # pseudo reference such as when file extracted from a
        # collection of modules contained in a zip file.

        if not os.path.isfile(path):
            return path in _times

        # Check for when file last modified.

        mtime = os.stat(path).st_mtime
        if path not in _times:
            _times[path] = mtime

        # Force restart when modification time has changed, even
        # if time now older, as that could indicate older file
        # has been restored.

        if mtime != _times[path]:
            return True
    except:
        # If any exception occured, likely that file has been
        # been removed just before stat(), so force a restart.

        return True

    return False

def _monitor():
    while 1:
        # Check modification times on all files in sys.modules.

        for module in sys.modules.values():
            if not hasattr(module, '__file__'):
                continue
            path = getattr(module, '__file__')
            if not path:
                continue
            if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
                path = path[:-1]
            if _modified(path):
                return _restart(path)

        # Check modification times on files which have
        # specifically been registered for monitoring.

        for path in _files:
            if _modified(path):
                return _restart(path)

        # Go to sleep for specified interval.

        try:
            return _queue.get(timeout=_interval)
        except:
            pass

_thread = threading.Thread(target=_monitor)
_thread.setDaemon(True)

def _exiting():
    try:
        _queue.put(True)
    except:
        pass
    _thread.join()

atexit.register(_exiting)

def track(path):
    if not path in _files:
        _files.append(path)

def start(interval=1.0):
    global _interval
    if interval < _interval:
        _interval = interval

    global _running
    _lock.acquire()
    if not _running:
        prefix = 'monitor (pid=%d):' % os.getpid()
        print('%s Starting change monitor.' % prefix, file=sys.stderr)
        _running = True
        _thread.start()
    _lock.release()

This would be used by importing into the script file the Python module
containing the above code, starting the monitoring system and adding any
additional non Python files which should be tracked:

import os

import monitor
monitor.start(interval=1.0)
monitor.track(os.path.join(os.path.dirname(__file__), 'site.cf'))

def application(environ, start_response):
    ...

Where needing to add many non Python files in a directory hierarchy, such
as template files which would otherwise be cached within the running
process, the os.path.walk() function could be used to traverse
all files and add required files based on extension or other criteria
using the 'track()' function.

This mechanism would generally work adequately where a single daemon
process is used within a process group. You would need to be careful
however when multiple daemon processes are used. This is because it may not
be possible to synchronise the checks exactly across all of the daemon
processes. As a result you may end up with the daemon processes running a
mixture of old and new code until they all synchronise with the new code
base. This problem can be minimised by defining a short interval time
between scans, however that will increase the overhead of the checks.

Using such an approach may in some cases be useful if using mod_wsgi as a
development platform. It certainly would not be recommended you use this
mechanism for a production system.

The reasons for not using it on a production system is due to the
additional overhead and chance that daemon processes are restarted when you
are not expecting them to be. For example, in a production environment
where requests are coming in all the time, you do not want a restart
triggered when you are part way through making a set of changes which cover
multiple files as likely then that an inconsistent set of code will be
loaded and the application will fail.

Note that you should also not use this mechanism on a system where you have
configured mod_wsgi to preload your WSGI application as soon as the daemon
process has started. If you do that, then the monitor thread will be recreated
immediately and so for every single code change on a preloaded file you
make, the daemon process will be restarted, even if there is no intervening
request.

If preloading was really required, the example code would need to be
modified so as to not use signals to restart the daemon process, but reset
to zero the variable saved away in the WSGI script file that records the
modification time of the script file. This will have the affect of delaying
the restart until the next request has arrived. Because that variable holding
the modification time is an internal implementation detail of mod_wsgi and
not strictly part of its published API or behaviour, you should only use
that approach if it is warranted.

Restarting Windows Apache¶

On the Windows platform there is no daemon mode only embedded mode. The MPM
used on Apache is the 'winnt' MPM. This MPM is like the worker MPM on UNIX
systems except that there is only one process.

Being embedded mode, modifying the WSGI script file only results in the WSGI
script file itself being reloaded, the process as a whole is not reloaded.
Thus there is no way normally through modifying the WSGI script file or any
other Python code file used by the application, of having the whole
application reloaded automatically.

The recipe in the previous section can be used with daemon mode on UNIX
systems to implement an automated scheme for restarting the daemon
processes when any code change is made, but because Windows lacks the
'fork()' system call daemon mode isn't supported in the first place.

Thus, the only way one can have code changes picked up on Windows is to
restart Apache as a whole. Although a full restart is required, Apache on
Windows only uses a single child server process and so the impact isn't as
significant as on UNIX platforms, where many processes may need to be
shutdown and restarted.

With that in mind, it is actually possible to modify the prior recipe for
restarting a daemon process to restart Apache itself. To achieve this slight
of hand, it is necessary to use the Python 'ctypes' module to get access to
a special internal Apache function which is available in the Windows version
of Apache called 'ap_signal_parent()'.

The required change to get this to work is to replace the restart
function in the previous code with the following:

def _restart(path):
    _queue.put(True)
    prefix = 'monitor (pid=%d):' % os.getpid()
    print('%s Change detected to \'%s\'.' % (prefix, path), file=sys.stderr)
    print('%s Triggering Apache restart.' % prefix, file=sys.stderr)
    import ctypes
    ctypes.windll.libhttpd.ap_signal_parent(1)

Other than that, the prior code would be used exactly as before. Now when
any change is made to Python code used by the application or any other
monitored files, Apache will be restarted automatically for you.

As before, probably recommended that this only be used during development
and not on a production system.

        Next

         Previous

        © Copyright 2007-2017, Graham Dumpleton.

  Built with Sphinx using a theme provided by Read the Docs.


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

<TITLE>
Uses of Class es.fnl.fsm.QueueItem
</TITLE>

<META NAME="date" CONTENT="2013-02-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
es.fnl.fsm.QueueItem

Uses of QueueItem in es.fnl.fsm

Fields in es.fnl.fsm declared as QueueItem

private  QueueItem<State<E>>
BFSQueue.start

Fields in es.fnl.fsm with type parameters of type QueueItem

private  Map<QueueItem<State<E>>,QueueItem<State<E>>>
BFSQueue.moves

private  Map<QueueItem<State<E>>,QueueItem<State<E>>>
BFSQueue.moves

private  Queue<QueueItem<State<E>>>
BFSQueue.queue

private  Map<QueueItem<State<E>>,Double>
BFSQueue.weights

Methods in es.fnl.fsm that return QueueItem

(package private)  QueueItem<State<E>>
BFSQueue.remove()

          Return the head of the queue.

Methods in es.fnl.fsm that return types with arguments of type QueueItem

(package private)  List<QueueItem<State<E>>>
BFSQueue.backtrack(QueueItem<State<E>> from)

          Find the list of states that were visited at each offset to reach this particular state.

Methods in es.fnl.fsm with parameters of type QueueItem

(package private)  void
BFSQueue.addTransistions(int off,
                QueueItem<State<E>> src,
                Set<State<E>> trgts,
                double w)

          Add the all target states that can be reached to the queue.

(package private)  List<QueueItem<State<E>>>
BFSQueue.backtrack(QueueItem<State<E>> from)

          Find the list of states that were visited at each offset to reach this particular state.

 int
QueueItem.compareTo(QueueItem<T> o)

          Implements the Comparable interface by sorting on the index value.

private  void
Matcher.setCaptureGroups(QueueItem<State<E>> item)

          Use weighted backtracking to identify capture groups based on a dynamic programming approach.

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import logo from './assets/logo.svg';
import './App.css';
import IconsBar from './components/IconsBar';
import Description from './components/Description';

class App extends Component {

  render() {
    return (

DEVELOPER / DESIGNER

          <Description />
          <IconsBar />

    );
  }
}

export default App;


text:
SCRIPT_TYPE = "CA"
TAGS = {
    {0, "Empty"},
    {1, "Full"},
    {2, "Empty up ant"},
    {3, "Empty right ant"},
    {4, "Empty down ant"},
    {5, "Empty left ant"},
    {6, "Full up ant"},
    {7, "Full right ant"},
    {8, "Full down ant"},
    {9, "Full left ant"}
}

NEIGHBORS_POS = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }
STATES_NUM = 10

-- States
empty = 0
full = 1

empty_up_ant = 2
empty_right_ant = 3
empty_down_ant = 4
empty_left_ant = 5

full_up_ant = 6
full_right_ant = 7
full_down_ant = 8
full_left_ant = 9

-- Rotations. To convert a rotation to a neighbor position in the neighbors array just add 1
up = 0
right = 1
down = 2
left = 3

function get_next_state (neighbors, state)
    -- If the ant was over this block flip it's value
    if block_under_ant(state) == empty then
        return full
    elseif block_under_ant(state) == full then
        return empty
    end

    -- The rotation of the ant on each block. If there is no ant the value will be -1
    local up_neigh = turn(neighbors[up + 1])
    local right_neigh = turn(neighbors[right + 1])
    local down_neigh = turn(neighbors[down + 1])
    local left_neigh = turn(neighbors[left + 1])

    -- The ant is heading this way
    if get_ant_rotation(up_neigh) == down then
        return set_ant(state, up_neigh)

    elseif get_ant_rotation(right_neigh) == left then
        return set_ant(state, right_neigh)

    elseif get_ant_rotation(down_neigh) == up then
        return set_ant(state, down_neigh)

    elseif get_ant_rotation(left_neigh) == right then
        return set_ant(state, left_neigh)
    end

    return state
end

function set_ant(block_state, ant_state)
    if block_state == empty then
        return 2 + get_ant_rotation(ant_state)
    else
        return 6 + get_ant_rotation(ant_state)
    end
end

function get_ant_rotation(state)
    if block_under_ant(state) == empty then
        return state - 2
    elseif block_under_ant(state) == full then
        return state - 6
    else
        return -1 -- there is no ant on this block
    end
end

function block_under_ant(state)
    if state >= 2 and state <= 5 then
        return empty
    elseif state >= 6 and state <= 9 then
        return full
    else
        return -1 -- there is no ant on the block
    end
end

function turn (state)
    if block_under_ant(state) == empty then -- if it empty under
        return (state + 1 + 2) % 4 + 2
    elseif block_under_ant(state) == full then
        return (state - 1 + 6) % 4 + 6
    else
        return state
    end
end


text:
#ifndef itkPNGImageIOFactory_h
#define itkPNGImageIOFactory_h
#include "ITKIOPNGExport.h"

#include "itkObjectFactoryBase.h"
#include "itkImageIOBase.h"

namespace itk
{
/**
 *\class PNGImageIOFactory
 * \brief Create instances of PNGImageIO objects using an object factory.
 * \ingroup ITKIOPNG
 */
class ITKIOPNG_EXPORT PNGImageIOFactory : public ObjectFactoryBase
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(PNGImageIOFactory);

  /** Standard class type aliases. */
  using Self = PNGImageIOFactory;
  using Superclass = ObjectFactoryBase;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Class methods used to interface with the registered factories. */
  const char *
  GetITKSourceVersion() const override;

  const char *
  GetDescription() const override;

  /** Method for class instantiation. */
  itkFactorylessNewMacro(Self);
  static PNGImageIOFactory *
  FactoryNew()
  {
    return new PNGImageIOFactory;
  }
  /** Run-time type information (and related methods). */
  itkTypeMacro(PNGImageIOFactory, ObjectFactoryBase);

  /** Register one factory of this type  */
  static void
  RegisterOneFactory()
  {
    auto pngFactory = PNGImageIOFactory::New();

    ObjectFactoryBase::RegisterFactoryInternal(pngFactory);
  }

protected:
  PNGImageIOFactory();
  ~PNGImageIOFactory() override;
};
} // end namespace itk

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="31">
	<title>Attendance and Use of the Science Library at M.I.T.	</title>
	<author>Bush, G.C.Galliher, H.P.Morse, P.M.	</author>
	<text>
		This is an interim report on continuing
		studies of library operations at Massachusetts
		Institute of Technology being made by
		members of the Institute's Operations Research
		Project in cooperation with the librarians and
		library staff.  In this report, which is based
		on actual observations of on-the-premise use
		made of the Science Library, various statistics
		measuring the kind, degree, and intensity of use
		are tabulated.  In addition there are some
		suggested measures of effectiveness of the library.
		A unique outcome of the survey has been the
		construction and verification of a mathematical
		model employing probability theory to measure
		rate and kind of use of library material
		together with length of stay of library patrons.
		Such models, characteristic of an operations
		research approach, give promise of furthering
		the goal of effective library management and
		planning.
	</text>
</article>


text:
<?php

namespace App\Http\Middleware;

use Closure;
use DB;

class CanInstall
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($this->alreadyInstalled()) {
            abort(404);
        }

        return $next($request);
    }

    /**
     * If application is already installed.
     *
     * @return bool
     */
    public function alreadyInstalled()
    {
        return file_exists(storage_path('installed'));
    }
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel source\modules\rbac\models\search\AssignmentSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Assignments';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Assignment', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'user',
            'role',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
#include <common.h>
#include <bootm.h>
#include <fdt_support.h>
#include <linux/libfdt.h>
#include <malloc.h>
#include <vxworks.h>
#include <tee/optee.h>

DECLARE_GLOBAL_DATA_PTR;

static int do_bootm_standalone(int flag, int argc, char * const argv[],
			       bootm_headers_t *images)
{
	char *s;
	int (*appl)(int, char *const[]);

	/* Don't start if "autostart" is set to "no" */
	s = env_get("autostart");
	if ((s != NULL) && !strcmp(s, "no")) {
		env_set_hex("filesize", images->os.image_len);
		return 0;
	}
	appl = (int (*)(int, char * const []))images->ep;
	appl(argc, argv);
	return 0;
}

/*******************************************************************/
/* OS booting routines */
/*******************************************************************/

#if defined(CONFIG_BOOTM_NETBSD) || defined(CONFIG_BOOTM_PLAN9)
static void copy_args(char *dest, int argc, char * const argv[], char delim)
{
	int i;

	for (i = 0; i < argc; i++) {
		if (i > 0)
			*dest++ = delim;
		strcpy(dest, argv[i]);
		dest += strlen(argv[i]);
	}
}
#endif

#ifdef CONFIG_BOOTM_NETBSD
static int do_bootm_netbsd(int flag, int argc, char * const argv[],
			    bootm_headers_t *images)
{
	void (*loader)(bd_t *, image_header_t *, char *, char *);
	image_header_t *os_hdr, *hdr;
	ulong kernel_data, kernel_len;
	char *cmdline;

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("NetBSD");
		return 1;
	}
#endif
	hdr = images->legacy_hdr_os;

	/*
	 * Booting a (NetBSD) kernel image
	 *
	 * This process is pretty similar to a standalone application:
	 * The (first part of an multi-) image must be a stage-2 loader,
	 * which in turn is responsible for loading & invoking the actual
	 * kernel.  The only differences are the parameters being passed:
	 * besides the board info strucure, the loader expects a command
	 * line, the name of the console device, and (optionally) the
	 * address of the original image header.
	 */
	os_hdr = NULL;
	if (image_check_type(&images->legacy_hdr_os_copy, IH_TYPE_MULTI)) {
		image_multi_getimg(hdr, 1, &kernel_data, &kernel_len);
		if (kernel_len)
			os_hdr = hdr;
	}

	if (argc > 0) {
		ulong len;
		int   i;

		for (i = 0, len = 0; i < argc; i += 1)
			len += strlen(argv[i]) + 1;
		cmdline = malloc(len);
		copy_args(cmdline, argc, argv, ' ');
	} else {
		cmdline = env_get("bootargs");
		if (cmdline == NULL)
			cmdline = "";
	}

	loader = (void (*)(bd_t *, image_header_t *, char *, char *))images->ep;

	printf("## Transferring control to NetBSD stage-2 loader (at address %08lx) ...\n",
	       (ulong)loader);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * NetBSD Stage-2 Loader Parameters:
	 *   arg[0]: pointer to board info data
	 *   arg[1]: image load address
	 *   arg[2]: char pointer to the console device to use
	 *   arg[3]: char pointer to the boot arguments
	 */
	(*loader)(gd->bd, os_hdr, "", cmdline);

	return 1;
}
#endif /* CONFIG_BOOTM_NETBSD*/

#ifdef CONFIG_LYNXKDI
static int do_bootm_lynxkdi(int flag, int argc, char * const argv[],
			     bootm_headers_t *images)
{
	image_header_t *hdr = &images->legacy_hdr_os_copy;

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("Lynx");
		return 1;
	}
#endif

	lynxkdi_boot((image_header_t *)hdr);

	return 1;
}
#endif /* CONFIG_LYNXKDI */

#ifdef CONFIG_BOOTM_RTEMS
static int do_bootm_rtems(int flag, int argc, char * const argv[],
			   bootm_headers_t *images)
{
	void (*entry_point)(bd_t *);

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("RTEMS");
		return 1;
	}
#endif

	entry_point = (void (*)(bd_t *))images->ep;

	printf("## Transferring control to RTEMS (at address %08lx) ...\n",
	       (ulong)entry_point);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * RTEMS Parameters:
	 *   r3: ptr to board info data
	 */
	(*entry_point)(gd->bd);

	return 1;
}
#endif /* CONFIG_BOOTM_RTEMS */

#if defined(CONFIG_BOOTM_OSE)
static int do_bootm_ose(int flag, int argc, char * const argv[],
			   bootm_headers_t *images)
{
	void (*entry_point)(void);

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("OSE");
		return 1;
	}
#endif

	entry_point = (void (*)(void))images->ep;

	printf("## Transferring control to OSE (at address %08lx) ...\n",
	       (ulong)entry_point);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * OSE Parameters:
	 *   None
	 */
	(*entry_point)();

	return 1;
}
#endif /* CONFIG_BOOTM_OSE */

#if defined(CONFIG_BOOTM_PLAN9)
static int do_bootm_plan9(int flag, int argc, char * const argv[],
			   bootm_headers_t *images)
{
	void (*entry_point)(void);
	char *s;

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("Plan 9");
		return 1;
	}
#endif

	/* See README.plan9 */
	s = env_get("confaddr");
	if (s != NULL) {
		char *confaddr = (char *)simple_strtoul(s, NULL, 16);

		if (argc > 0) {
			copy_args(confaddr, argc, argv, '\n');
		} else {
			s = env_get("bootargs");
			if (s != NULL)
				strcpy(confaddr, s);
		}
	}

	entry_point = (void (*)(void))images->ep;

	printf("## Transferring control to Plan 9 (at address %08lx) ...\n",
	       (ulong)entry_point);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * Plan 9 Parameters:
	 *   None
	 */
	(*entry_point)();

	return 1;
}
#endif /* CONFIG_BOOTM_PLAN9 */

#if defined(CONFIG_BOOTM_VXWORKS) && \
	(defined(CONFIG_PPC) || defined(CONFIG_ARM))

void do_bootvx_fdt(bootm_headers_t *images)
{
#if defined(CONFIG_OF_LIBFDT)
	int ret;
	char *bootline;
	ulong of_size = images->ft_len;
	char **of_flat_tree = &images->ft_addr;
	struct lmb *lmb = &images->lmb;

	if (*of_flat_tree) {
		boot_fdt_add_mem_rsv_regions(lmb, *of_flat_tree);

		ret = boot_relocate_fdt(lmb, of_flat_tree, &of_size);
		if (ret)
			return;

		/* Update ethernet nodes */
		fdt_fixup_ethernet(*of_flat_tree);

		ret = fdt_add_subnode(*of_flat_tree, 0, "chosen");
		if ((ret >= 0 || ret == -FDT_ERR_EXISTS)) {
			bootline = env_get("bootargs");
			if (bootline) {
				ret = fdt_find_and_setprop(*of_flat_tree,
						"/chosen", "bootargs",
						bootline,
						strlen(bootline) + 1, 1);
				if (ret < 0) {
					printf("## ERROR: %s : %s\n", __func__,
					       fdt_strerror(ret));
					return;
				}
			}
		} else {
			printf("## ERROR: %s : %s\n", __func__,
			       fdt_strerror(ret));
			return;
		}
	}
#endif

	boot_prep_vxworks(images);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

#if defined(CONFIG_OF_LIBFDT)
	printf("## Starting vxWorks at 0x%08lx, device tree at 0x%08lx ...\n",
	       (ulong)images->ep, (ulong)*of_flat_tree);
#else
	printf("## Starting vxWorks at 0x%08lx\n", (ulong)images->ep);
#endif

	boot_jump_vxworks(images);

	puts("## vxWorks terminated\n");
}

static int do_bootm_vxworks(int flag, int argc, char * const argv[],
			     bootm_headers_t *images)
{
	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("VxWorks");
		return 1;
	}
#endif

	do_bootvx_fdt(images);

	return 1;
}
#endif

#if defined(CONFIG_CMD_ELF)
static int do_bootm_qnxelf(int flag, int argc, char * const argv[],
			    bootm_headers_t *images)
{
	char *local_args[2];
	char str[16];
	int dcache;

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("QNX");
		return 1;
	}
#endif

	sprintf(str, "%lx", images->ep); /* write entry-point into string */
	local_args[0] = argv[0];
	local_args[1] = str;	/* and provide it via the arguments */

	/*
	 * QNX images require the data cache is disabled.
	 */
	dcache = dcache_status();
	if (dcache)
		dcache_disable();

	do_bootelf(NULL, 0, 2, local_args);

	if (dcache)
		dcache_enable();

	return 1;
}
#endif

#ifdef CONFIG_INTEGRITY
static int do_bootm_integrity(int flag, int argc, char * const argv[],
			   bootm_headers_t *images)
{
	void (*entry_point)(void);

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

#if defined(CONFIG_FIT)
	if (!images->legacy_hdr_valid) {
		fit_unsupported_reset("INTEGRITY");
		return 1;
	}
#endif

	entry_point = (void (*)(void))images->ep;

	printf("## Transferring control to INTEGRITY (at address %08lx) ...\n",
	       (ulong)entry_point);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * INTEGRITY Parameters:
	 *   None
	 */
	(*entry_point)();

	return 1;
}
#endif

#ifdef CONFIG_BOOTM_OPENRTOS
static int do_bootm_openrtos(int flag, int argc, char * const argv[],
			   bootm_headers_t *images)
{
	void (*entry_point)(void);

	if (flag != BOOTM_STATE_OS_GO)
		return 0;

	entry_point = (void (*)(void))images->ep;

	printf("## Transferring control to OpenRTOS (at address %08lx) ...\n",
		(ulong)entry_point);

	bootstage_mark(BOOTSTAGE_ID_RUN_OS);

	/*
	 * OpenRTOS Parameters:
	 *   None
	 */
	(*entry_point)();

	return 1;
}
#endif

#ifdef CONFIG_BOOTM_OPTEE
static int do_bootm_tee(int flag, int argc, char * const argv[],
			bootm_headers_t *images)
{
	int ret;

	/* Verify OS type */
	if (images->os.os != IH_OS_TEE) {
		return 1;
	};

	/* Validate OPTEE header */
	ret = optee_verify_bootm_image(images->os.image_start,
				       images->os.load,
				       images->os.image_len);
	if (ret)
		return ret;

	/* Locate FDT etc */
	ret = bootm_find_images(flag, argc, argv);
	if (ret)
		return ret;

	/* From here we can run the regular linux boot path */
	return do_bootm_linux(flag, argc, argv, images);
}
#endif

static boot_os_fn *boot_os[] = {
	[IH_OS_U_BOOT] = do_bootm_standalone,
#ifdef CONFIG_BOOTM_LINUX
	[IH_OS_LINUX] = do_bootm_linux,
#endif
#ifdef CONFIG_BOOTM_NETBSD
	[IH_OS_NETBSD] = do_bootm_netbsd,
#endif
#ifdef CONFIG_LYNXKDI
	[IH_OS_LYNXOS] = do_bootm_lynxkdi,
#endif
#ifdef CONFIG_BOOTM_RTEMS
	[IH_OS_RTEMS] = do_bootm_rtems,
#endif
#if defined(CONFIG_BOOTM_OSE)
	[IH_OS_OSE] = do_bootm_ose,
#endif
#if defined(CONFIG_BOOTM_PLAN9)
	[IH_OS_PLAN9] = do_bootm_plan9,
#endif
#if defined(CONFIG_BOOTM_VXWORKS) && \
	(defined(CONFIG_PPC) || defined(CONFIG_ARM))
	[IH_OS_VXWORKS] = do_bootm_vxworks,
#endif
#if defined(CONFIG_CMD_ELF)
	[IH_OS_QNX] = do_bootm_qnxelf,
#endif
#ifdef CONFIG_INTEGRITY
	[IH_OS_INTEGRITY] = do_bootm_integrity,
#endif
#ifdef CONFIG_BOOTM_OPENRTOS
	[IH_OS_OPENRTOS] = do_bootm_openrtos,
#endif
#ifdef CONFIG_BOOTM_OPTEE
	[IH_OS_TEE] = do_bootm_tee,
#endif
};

/* Allow for arch specific config before we boot */
__weak void arch_preboot_os(void)
{
	/* please define platform specific arch_preboot_os() */
}

int boot_selected_os(int argc, char * const argv[], int state,
		     bootm_headers_t *images, boot_os_fn *boot_fn)
{
	arch_preboot_os();
	boot_fn(state, argc, argv, images);

	/* Stand-alone may return when 'autostart' is 'no' */
	if (images->os.type == IH_TYPE_STANDALONE ||
	    IS_ENABLED(CONFIG_SANDBOX) ||
	    state == BOOTM_STATE_OS_FAKE_GO) /* We expect to return */
		return 0;
	bootstage_error(BOOTSTAGE_ID_BOOT_OS_RETURNED);
	debug("\n## Control returned to monitor - resetting...\n");

	return BOOTM_ERR_RESET;
}

boot_os_fn *bootm_os_get_boot_func(int os)
{
#ifdef CONFIG_NEEDS_MANUAL_RELOC
	static bool relocated;

	if (!relocated) {
		int i;

		/* relocate boot function table */
		for (i = 0; i < ARRAY_SIZE(boot_os); i++)
			if (boot_os[i] != NULL)
				boot_os[i] += gd->reloc_off;

		relocated = true;
	}
#endif
	return boot_os[os];
}


text:
layout: post
title: Membuat Profil Firefox dengan Bantuan Firefox Profilemaker
tags: [firefox, profile, security, privacy]
comments: true
---

Peramban situs web kini ibarat sistem operasi tersendiri. Bukan lagi sekadar penampil berkas HTML, melainkan juga berkas multimedia. [Google Chromebooks](https://www.google.com/chromebook/) merupakan bukti nyata bahwa peramban web sanggup menjadi sistem operasi (atau setidaknya menjadi antarmuka grafis) mandiri.

_With great power, come great responsibility_...
Seiring bertambahnya tugas yang mesti dipikul, maka peramban pun tumbuh menjadi sosok yang rakus sumberdaya komputer, rumit, dan menjadi salah satu celah keamanan.
Celah keamanan? Yep, peramban web sekarang lumayan menyeramkan, tidak hanya bisa membaca HTML, namun juga bisa merekam video dan suara, menentukan letak, mengetahui kapasitas batere, dan banyak lagi.

Dari banyak peramban web yang kini beredar, jika diusut akan mengerucut pada dua buah peramban besar; yakni Google Chrome dan Mozilla Firefox.
Sebagai seorang pengguna Firefox, saya sering kali buta dengan fitur-fitur dari Firefox itu sendiri; apa fungsi A? Bagaimana mematikan fitur B? Dan lain sebagainya.
Artikel kali ini akan membahas bagaimana kita memahami dan menyesuaikan pengaturan Firefox agar sesuai yang kita inginkan.

Kita bisa saja mengatur fitur-fitur di Firefox satu-per-satu secara manual, namun dengan banyaknya fitur, letaknya yang acak, dan dokumentasi yang minim dalam perambannya itu sendiri, menjadikan langkah mengatur secara manual ini membosankan.

Memperkenalkan, [Firefox Profilmaker](https://ffprofile.com/). Sebuah laman web yang akan membantu kita membuat profil sesuai kehendak. Begini caranya:

1. Kunjungi laman [ffprofile](https://ffprofile.com/) dan lalui tahapannya. Baca dengan seksama setiap parameter dan kegunaannya, hingga kita akan paham apa yang terbaik.
1. Setelah sampai pada tahap _finish_, unduh `profile.zip` hasil pilihan kita pada langkah pertama.
1. Buat sebuah profil baru (atau bisa juga menggunakan yang telah ada)
1. Ketik `about:support` pada _url bar_.
1. Tekan tombol _Open Directory_ pada baris _Profile Directory_, langkah ini akan membuka sebuah jendela _file manager_ pada direktori profil yang terpilih.
1. Tutup Firefox.
1. Hapus semua isi direktori profil di langkah 5.
1. Uraikan `profile.zip` yang telah diunduh di langkah kedua ke dalam direktori profil yang telah dikosongkan isinya tadi.
1. Jalankan kembali Firefox. Jika tadi membuat profil baru, jalankan dengan `firefox -no-remote -P namaprofil`
1. Buka _addon manager_ dan mutakhirkan isinya.

_Easy isn't it?_
_Thanx for reading, see you on next article..._


text:
import { DialogService } from './dialog.service';
import { DialogContainerComponent } from './dialog-container/dialog-container.component';
import { TestBed } from '@angular/core/testing';
import {
  Directive,
  Component,
  NgModule,
  ApplicationRef,
  TemplateRef,
  ViewChild
} from '@angular/core';

@Component({
  template: 'some dialog {{someVariable}}'
})
class DialogServiceTestComponent {
  someVariable = 'default string';
}

@Directive({
  selector: '[dialogTest]'
})
class DialogTestDirective {
  constructor(public template: TemplateRef<any>) {

  }
}

@Component({
  template: '<ng-template dialogTest></ng-template>'
})
class DialogServiceTest2Component {
  @ViewChild(DialogTestDirective,  { static: true }) directive: DialogTestDirective;
}

@NgModule({
  declarations: [
    DialogContainerComponent,
    DialogServiceTestComponent,
    DialogServiceTest2Component,
    DialogTestDirective
  ],
  entryComponents: [DialogContainerComponent, DialogServiceTestComponent]
})
class TestModule {

}

class TestClass {
  someVariable() {}
}

describe('dialog.service', () => {
  let dialogService: DialogService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [],
      providers: [DialogService],
      imports: [TestModule]
    });
    dialogService = TestBed.get(DialogService);
  });

  afterEach(() => {
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(0);
  });

  it('appends a container to the body and is able to remove it', () => {
    const dialog = dialogService.open(DialogServiceTestComponent);
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(1);
    dialog.close();
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(0);
  });

  it('only opens one dialog at a time', () => {
    dialogService.open(DialogServiceTestComponent);
    dialogService.open(DialogServiceTestComponent);
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(1);
    dialogService.close();
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(0);
  });

  it('does not throw an error when no option is provided', () => {
    expect(() => dialogService.open(DialogServiceTestComponent)).not.toThrow();
    dialogService.close();
  });

  it('initializes the members of the projected content', () => {
    dialogService.open(DialogServiceTestComponent, undefined, {
      someVariable: 'here it is'
    });
    const appRef: ApplicationRef = TestBed.get(ApplicationRef);
    appRef.tick();
    expect(document.body.querySelectorAll('iw-dialog-container').item(0).textContent.trim()).toBe('some dialog here it is');
    dialogService.close();
  });

  it('opens with a TemplateRef given', () => {
    const fixture = TestBed.createComponent(DialogServiceTest2Component);
    const component = fixture.componentInstance;
    dialogService.openTemplateRef(component.directive.template, null, {});
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(1);
    dialogService.close();
  });

  it('opens with a TemplateRef given and closes it', () => {
    const fixture = TestBed.createComponent(DialogServiceTest2Component);
    const component = fixture.componentInstance;
    dialogService.openTemplateRef(component.directive.template, null, {});
    dialogService.close();
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(0);
  });

  it('opens with a TemplateRef given and closes it with the IDialog reference', () => {
    const fixture = TestBed.createComponent(DialogServiceTest2Component);
    const component = fixture.componentInstance;
    const dialog = dialogService.openTemplateRef(component.directive.template, null, {});
    dialog.close();
    expect(document.body.querySelectorAll('iw-dialog-container').length).toBe(0);
  });

  it('excludes non property values', () => {
    const dialog = dialogService.open(DialogServiceTestComponent, {}, new TestClass());
    const appRef: ApplicationRef = TestBed.get(ApplicationRef);
    appRef.tick();
    expect(document.body.querySelectorAll('iw-dialog-container').item(0).textContent.trim()).toBe('some dialog default string');
    dialog.close();
  });

  it('does not throw when calling close on an already closed dialog', () => {
    expect(() => {
      const dialog = dialogService.open(DialogServiceTestComponent, {}, new TestClass());
      const dialog2 = dialogService.open(DialogServiceTestComponent, {}, new TestClass());
      dialog.close();
      dialog2.close();
    }).not.toThrow();
  });

});


text:
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkVTKImageIOFactory_h
#define itkVTKImageIOFactory_h
#include "ITKIOVTKExport.h"

#include "itkObjectFactoryBase.h"
#include "itkImageIOBase.h"

namespace itk
{
/** \class VTKImageIOFactory
 * \brief Create instances of VTKImageIO objects using an object factory.
 * \ingroup ITKIOVTK
 */
class ITKIOVTK_EXPORT VTKImageIOFactory:public ObjectFactoryBase
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(VTKImageIOFactory);

  /** Standard class type aliases. */
  using Self = VTKImageIOFactory;
  using Superclass = ObjectFactoryBase;
  using Pointer = SmartPointer< Self >;
  using ConstPointer = SmartPointer< const Self >;

  /** Class Methods used to interface with the registered factories. */
  const char * GetITKSourceVersion() const override;

  const char * GetDescription() const override;

  /** Method for class instantiation. */
  itkFactorylessNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(VTKImageIOFactory, ObjectFactoryBase);

  /** Register one factory of this type  */
  static void RegisterOneFactory()
  {
    VTKImageIOFactory::Pointer vtkFactory = VTKImageIOFactory::New();

    ObjectFactoryBase::RegisterFactoryInternal(vtkFactory);
  }

protected:
  VTKImageIOFactory();
  ~VTKImageIOFactory() override;
};
} // end namespace itk

#endif


text:
var args = arguments[0] || {};
var viewFile=require('viewFile').viewFile;
var e={
	init:function(){
		this.getData();
		this.setEvent();
	}
	,setEvent:function(){
		$.transDetail.addEventListener('click',function(){
			var basicui=new basicUI(true,false);
			var win1=basicui.getBasic_win();
			var mainView=basicui.getContentView();
			var url=Alloy.Globals.webLink+'transDetailMobile.php?id='+args.number;
			 var webView = Titanium.UI.createWebView({url:url});
			 mainView.add(webView);
			 win1.open();
		});
	}
	,getData:function(){

		xhr.request({
					postData:{mid:args.number},
					url:'getTransDetailProp.php?mid='+args.number,
					success:function(e){

						e=e[0];

						$.fulladdr.text=e.FULLADDR;
						$.memorial_date.text=e.MEMORIAL_DATE;
						$.district.text=e.DISTRICT;
						$.gfa.text=e.GFA;
						$.nfa.text=e.NFA;
						$.price.text=e.PRICE;
						$.avggfa.text=e.AVGGFA;
						$.natinst.text=e.NATINST;
						$.usage.text=e.USAGE;

					}
					,error:function(e){
						console.log(e);

					}
				});
	}

};

e.init();


text:
from __future__ import absolute_import, print_function, division

import numpy as np
import os
from scipy import interpolate
import sqlite3

from .. import df

col_dict = {'sdss': 'm_ini, m_act, u, g, r, i, z, J, H, Ks',
            'des': 'm_ini, m_act, u, g, r, i, z, Y'}

class SSP(object):
    def __init__(self, age, met, mf='kroupa', **kwargs):

        self.age = age
        self.met = met
        self._ISOCDIR = kwargs['isocdir']
        self.col_dict = col_dict

        try:
           self.isoc = self._getiso(group=kwargs['group'],
                                    filterset=kwargs['filterset'])
        except:
           self.isoc = self._getiso()

        self.max_mass = np.max(self.isoc[:,0])
        self.min_mass = np.min(self.isoc[:,0])

        if mf == 'kroupa':
            try:
                # Try to use values given by user.
                self.mf = df.Kroupa(kwargs['a'], kwargs['mlim'])
            except:
                # Fall back to default if not given
                self.mf = df.Kroupa()
        elif mf == 'user':
            try:
                self.mf = df.UserMF(kwargs['mass'])
            except:
                print("Give me a mass array")
                raise ValueError
        elif mf == 'texp':
            # Not implemented
            # self.mf = df.TaperedExp()
            raise ValueError("Not implemented")
        else:
            raise ValueError("Not implemented or inexistent")

    def populate(self, n=10000, fbin=0.0):

        flux = lambda x: 10**(-x/2.5)

        self.n = n
        try:
            masses = self.mf.sample(n)
        except:
            # User mass array
            masses = self.mf.sample()

        # Total mass sampled from the full IMF
        total_mass = sum(masses)

        # Mask to exclude values outside the range covered by the model
        mask = (masses < self.max_mass)&(masses > self.min_mass)
        masses = masses[mask]
        n = len(masses)

        ivals = self._interpolate()
        stars = np.array(masses)
        for vname in self.cols[1:]:
            stars = np.c_[stars, ivals[vname](masses)]

        if fbin > 0.0:
            print("Binaries are buggy, beware")
            magic = 0.63
            idx = np.random.randint(int(n*fbin), size=int((1.0/magic)*n*fbin))
            cmasses = self.mf.sample(len(idx))
            for i, vname in enumerate(self.cols[2:]):
                stars[idx, i+2] = -2.5*np.log10(flux(stars[idx, i+2]) +
                                                flux(ivals[vname](cmasses)))

        elif 1.0 < fbin < 0.0:
            raise ValueError("f_bin must be less than 1 and positive")

        self._stars = stars
        self._total_mass = total_mass

        return total_mass, stars

    def _getiso (self, group='padova12', filterset='des'):
        """
        Find the corresponding isochrone for a given age and metallicity
        """

        age = self.age
        met = self.met

        _ISOCDIR = self._ISOCDIR

        table_name = 'padova_'+filterset
        self.cols = col_dict[filterset].split()

        print(_ISOCDIR)
        connection=sqlite3.connect(_ISOCDIR+'/isoc_'+group+'_'+filterset+'.sqlite')
        cursor=connection.cursor()

        # this return a list of tuples
        cursor.execute('SELECT Z_met FROM met_grid ORDER BY ABS(Z_met - '+str(met)+') LIMIT 1')
        n_Z = cursor.fetchall()[0][0]

        cursor.execute('SELECT lage FROM age_grid ORDER BY ABS(lage - '+str(age)+') LIMIT 1')
        n_age = cursor.fetchall()[0][0]

        if float(n_Z) != met or float(n_age) != age:
            print("Model with Z = "+str(met)+" and log(age/yr) = "+str(age)+" not found.")
            print("Using Z = "+str(n_Z)+" and log(age/yr) = "+str(n_age))
        else:
            print("Using Z = "+str(n_Z)+" and log(age/yr) = "+str(n_age))

        age = str(n_age)
        met = str(n_Z)
        cursor.execute('SELECT '+ col_dict[filterset] +' FROM '+table_name+' WHERE lage = '+age+' AND Z_met = '+met)
        self.isoc = np.asarray(cursor.fetchall())
        self.age = n_age
        self.met = n_Z

        return self.isoc

    def _interpolate(self):
        """
        This method can be generalized to interpolate any quantity given in the
        isochrone table.

        NOTES:
            - higher order interpolation are broken. Scipy.interpolate.interp1d
              does not provide a good solution. Why?
        """
        m = {}
        z = self.isoc[:,0] # mass array
        for idx, name in enumerate(self.cols):
            m[name] = interpolate.interp1d(z, self.isoc[:,idx],
                                           bounds_error=False)

        return m

    def _setisocdir(self, dir):

        self._ISOCDIR = dir
        return


text:
package com.braintreepayments.api.internal;

import com.braintreepayments.api.BuildConfig;
import com.braintreepayments.api.EnvironmentHelper;
import com.braintreepayments.api.exceptions.UnexpectedException;

import junit.framework.TestCase;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Locale;

public class HttpRequestTest extends TestCase {

    private HttpRequest mHttpRequest;

    @Override
    public void setUp() {
        HttpRequest.DEBUG = true;
        mHttpRequest = new HttpRequest("myAuthorizationToken");
    }

    public void testSendsUserAgent() throws IOException {
        HttpURLConnection connection = mHttpRequest.init("http://example.com");
        assertEquals("braintree/android/" + BuildConfig.VERSION_NAME,
                connection.getRequestProperty("User-Agent"));
    }

    public void testSendsAcceptLanguageHeader() throws IOException {
        HttpURLConnection connection = mHttpRequest.init("http://example.com");
        assertEquals(Locale.getDefault().getLanguage(),
                connection.getRequestProperty("Accept-Language"));
    }

    public void testSendsContentType() throws IOException {
        HttpURLConnection connection = mHttpRequest.init("http://example.com");
        assertEquals("application/json", connection.getRequestProperty("Content-Type"));
    }

    public void testSetsAuthorizationTokenOnGet() throws UnexpectedException {
        assertEquals(EnvironmentHelper.getGatewayPath() + "/v1/payment_methods?authorizationFingerprint=myAuthorizationToken",
                mHttpRequest.get(EnvironmentHelper.getGatewayPath() + "/v1/payment_methods").getUrl());
    }

    public void testSetsAuthorizationTokenOnPost() throws UnexpectedException {
        assertTrue(mHttpRequest.post(EnvironmentHelper.getGatewayPath(), "{}").getData()
                .contains("myAuthorizationToken"));
    }

    public void testGetRequestSslCertificateSuccessfulInSandbox() throws UnexpectedException {
        int statusCode = mHttpRequest
                .get("https://api.sandbox.braintreegateway.com")
                .getResponseCode();

        assertEquals(200, statusCode);
    }

    public void testGetRequestSslCertificateSuccessfulInProduction() throws UnexpectedException {
        int statusCode = mHttpRequest
                .get("https://api.braintreegateway.com")
                .getResponseCode();

        assertEquals(200, statusCode);
    }

    public void testHostnameVerificationFailsForIncorrectHostName() {
        try {
            mHttpRequest.get("https://204.109.13.121:443");
            fail();
        } catch (Exception e) {
            assertEquals("Hostname '204.109.13.121' was not verified", e.getMessage());
        }
    }

    public void testGetRequestBadCertificateCheck() {
        if (!BuildConfig.RUN_ALL_TESTS) {
            return;
        }
        try {
            mHttpRequest.get("https://" + EnvironmentHelper.getLocalhostIp() + ":9443");
            fail();
        } catch (Exception e) {
            // @formatter:off
            assertEquals("java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.", e.getMessage());
            // @formatter:on
        }
    }
}


text:
package validator;

import domain.Entity;
import exception.IdValidatorException;

/**
 * Created by claudiu on 16.10.2016.
 */
public class IdValidator {
    public void validate(int id, int lastId) throws IdValidatorException {
        if (id > lastId) {
            throw new IdValidatorException("This id dosen't exist");
        }
    }
}


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

<TITLE>
Zip
</TITLE>

<META NAME="date" CONTENT="2011-06-20">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.openqa.selenium.io

Class Zip

java.lang.Object
  org.openqa.selenium.io.Zip

public class Zip
extends java.lang.Object

Constructor Summary

Zip()

Method Summary

 void
unzip(java.io.File source,
      java.io.File outputDir)

 void
unzip(java.io.InputStream source,
      java.io.File outputDir)

 void
unzip(java.lang.String source,
      java.io.File outputDir)

 void
unzipFile(java.io.File output,
          java.io.InputStream zipStream,
          java.lang.String name)

 java.lang.String
zip(java.io.File inputDir)

 void
zip(java.io.File inputDir,
    java.io.File output)

Methods inherited from class java.lang.Object

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

Constructor Detail

Zip

public Zip()

Method Detail

zip

public void zip(java.io.File inputDir,
                java.io.File output)
         throws java.io.IOException

Throws:

java.io.IOException

zip

public java.lang.String zip(java.io.File inputDir)
                     throws java.io.IOException

Throws:

java.io.IOException

unzip

public void unzip(java.lang.String source,
                  java.io.File outputDir)
           throws java.io.IOException

Throws:

java.io.IOException

unzip

public void unzip(java.io.File source,
                  java.io.File outputDir)
           throws java.io.IOException

Throws:

java.io.IOException

unzip

public void unzip(java.io.InputStream source,
                  java.io.File outputDir)
           throws java.io.IOException

Throws:

java.io.IOException

unzipFile

public void unzipFile(java.io.File output,
                      java.io.InputStream zipStream,
                      java.lang.String name)
               throws java.io.IOException

Throws:

java.io.IOException

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
"""
Test cases for Pet Model

Test cases can be run with:
  nosetests
  coverage report -m
"""

import unittest
from app.models import Pet, DataValidationError

######################################################################
#  T E S T   C A S E S
######################################################################
class TestPets(unittest.TestCase):
    """ Test Cases for Pets """

    def setUp(self):
        Pet.remove_all()

    def test_create_a_pet(self):
        """ Create a pet and assert that it exists """
        pet = Pet(0, "fido", "dog")
        self.assertTrue(pet != None)
        self.assertEqual(pet.id, 0)
        self.assertEqual(pet.name, "fido")
        self.assertEqual(pet.category, "dog")

    def test_add_a_pet(self):
        """ Create a pet and add it to the database """
        pets = Pet.all()
        self.assertEqual(pets, [])
        pet = Pet(0, "fido", "dog")
        self.assertTrue(pet != None)
        self.assertEqual(pet.id, 0)
        pet.save()
        # Asert that it was assigned an id and shows up in the database
        self.assertEqual(pet.id, 1)
        pets = Pet.all()
        self.assertEqual(len(pets), 1)

    def test_update_a_pet(self):
        """ Update a Pet """
        pet = Pet(0, "fido", "dog")
        pet.save()
        self.assertEqual(pet.id, 1)
        # Change it an save it
        pet.category = "k9"
        pet.save()
        self.assertEqual(pet.id, 1)
        # Fetch it back and make sure the id hasn't changed
        # but the data did change
        pets = Pet.all()
        self.assertEqual(len(pets), 1)
        self.assertEqual(pets[0].category, "k9")

    def test_delete_a_pet(self):
        """ Delete a Pet """
        pet = Pet(0, "fido", "dog")
        pet.save()
        self.assertEqual(len(Pet.all()), 1)
        # delete the pet and make sure it isn't in the database
        pet.delete()
        self.assertEqual(len(Pet.all()), 0)

    def test_serialize_a_pet(self):
        """ Test serialization of a Pet """
        pet = Pet(0, "fido", "dog")
        data = pet.serialize()
        self.assertNotEqual(data, None)
        self.assertIn('id', data)
        self.assertEqual(data['id'], 0)
        self.assertIn('name', data)
        self.assertEqual(data['name'], "fido")
        self.assertIn('category', data)
        self.assertEqual(data['category'], "dog")

    def test_deserialize_a_pet(self):
        """ Test deserialization of a Pet """
        data = {"id": 1, "name": "kitty", "category": "cat"}
        pet = Pet()
        pet.deserialize(data)
        self.assertNotEqual(pet, None)
        self.assertEqual(pet.id, 0) # id should be ignored
        self.assertEqual(pet.name, "kitty")
        self.assertEqual(pet.category, "cat")
        # test with id passed into constructor
        pet = Pet(1)
        pet.deserialize(data)
        self.assertNotEqual(pet, None)
        self.assertEqual(pet.id, 1)
        self.assertEqual(pet.name, "kitty")
        self.assertEqual(pet.category, "cat")

    def test_deserialize_with_no_name(self):
        """ Deserialize a Pet without a name """
        pet = Pet()
        data = {"id":0, "category": "cat"}
        self.assertRaises(DataValidationError, pet.deserialize, data)

    def test_deserialize_with_no_data(self):
        """ Deserialize a Pet with no data """
        pet = Pet()
        self.assertRaises(DataValidationError, pet.deserialize, None)

    def test_deserialize_with_bad_data(self):
        """ Deserailize a Pet with bad data """
        pet = Pet()
        self.assertRaises(DataValidationError, pet.deserialize, "data")

    def test_find_pet(self):
        """ Find a Pet by ID """
        Pet(0, "fido", "dog").save()
        Pet(0, "kitty", "cat").save()
        pet = Pet.find(2)
        self.assertIsNot(pet, None)
        self.assertEqual(pet.id, 2)
        self.assertEqual(pet.name, "kitty")

    def test_find_with_no_pets(self):
        """ Find a Pet with no Pets """
        pet = Pet.find(1)
        self.assertIs(pet, None)

    def test_pet_not_found(self):
        """ Test for a Pet that doesn't exist """
        Pet(0, "fido", "dog").save()
        pet = Pet.find(2)
        self.assertIs(pet, None)

    def test_find_by_category(self):
        """ Find Pets by Category """
        Pet(0, "fido", "dog").save()
        Pet(0, "kitty", "cat").save()
        pets = Pet.find_by_category("cat")
        self.assertNotEqual(len(pets), 0)
        self.assertEqual(pets[0].category, "cat")
        self.assertEqual(pets[0].name, "kitty")

    def test_find_by_name(self):
        """ Find a Pet by Name """
        Pet(0, "fido", "dog").save()
        Pet(0, "kitty", "cat").save()
        pets = Pet.find_by_name("kitty")
        self.assertEqual(len(pets), 1)
        self.assertEqual(pets[0].category, "cat")
        self.assertEqual(pets[0].name, "kitty")

######################################################################
#   M A I N
######################################################################
if __name__ == '__main__':
    unittest.main()
    # suite = unittest.TestLoader().loadTestsFromTestCase(TestPets)
    # unittest.TextTestRunner(verbosity=2).run(suite)


text:
module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: [
    "@typescript-eslint",
  ],
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
  ],
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: "module",
    ecmaFeatures: {}
  },
  globals: {
    "BigInt64Array": "readonly",
    "BigUint64Array": "readonly",
    "__non_webpack_require__": "readonly"
  },

  // === General rules =========================================================

  rules: {
    // Omitted semicolons are hugely popular, yet within the compiler it makes
    // sense to be better safe than sorry.
    "semi": "error",

    // Our code bases uses 2 spaces for indentation, and we enforce it here so
    // files don't mix spaces, tabs or different indentation levels.
    "indent": ["error", 2, {
      "SwitchCase": 1,
      "VariableDeclarator": "first",
      "offsetTernaryExpressions": true,
      "ignoredNodes": [ // FIXME: something's odd here
        "ConditionalExpression > *",
        "ConditionalExpression > * > *",
        "ConditionalExpression > * > * > *"
      ]
    }],

    // This is mostly visual style, making comments look uniform.
    "spaced-comment": ["error", "always", {
      "markers": ["/"],   // triple-slash
      "exceptions": ["/"] // all slashes
    }],

    // This tends to be annoying as it encourages developers to make everything
    // that is never reassigned a 'const', sometimes semantically incorrect so,
    // typically leading to huge diffs in follow-up PRs modifying affected code.
    "prefer-const": "off",

    // It is perfectly fine to declare top-level variables with `var`, yet this
    // rule doesn't provide configuration options that would help.
    "no-var": "off",

    // Quite often, dealing with multiple related cases at once or otherwise
    // falling through is exactly the point of using a switch.
    "no-fallthrough": "off",

    // Typical false-positives here are `do { ... } while (true)` statements or
    // similar, but the only option provided here is not checking any loops.
    "no-constant-condition": ["error", { checkLoops: false }],

    // Functions are nested in blocks occasionally, and there haven't been any
    // problems with this so far, so turning the check off.
    "no-inner-declarations": "off",

    // Quite common in scenarios where an iteration starts at `current = this`.
    "@typescript-eslint/no-this-alias": "off",

    // Interferes with tests and 64-bit literals
    "@typescript-eslint/no-loss-of-precision": "off",

    // Disabled here, but enabled again for JavaScript files.
    "no-unused-vars": "off",

    // Disabled here, but enabled again for TypeScript files.
    "@typescript-eslint/no-unused-vars": "off"
  },
  overrides: [

    // === JavaScript rules ====================================================

    {
      env: {
        "browser": true,
        "amd": true,
        "node": true,
        "es6": true
      },
      files: [
        "**/*.js",
        "bin/*"
      ],
      rules: {
        // We are testing both ESM and UMD, so don't limit us.
        "@typescript-eslint/no-var-requires": "off",

        // This rule does not behave well in JS files.
        "@typescript-eslint/explicit-module-boundary-types": "off",

        // Enforcing to remove function parameters on stubs makes code less
        // maintainable, so we instead allow unused function parameters.
        "no-unused-vars": [
          "warn", {
            "vars": "local",
            "args": "none",
            "ignoreRestSiblings": false
          }
        ],

        "@typescript-eslint/no-loss-of-precision": "error",
      }
    },

    // === TypeScript rules ====================================================

    {
      files: [
        "**/*.ts"
      ],
      rules: {
        // Enforcing to remove function parameters on stubs makes code less
        // maintainable, so we instead allow unused function parameters.
        "@typescript-eslint/no-unused-vars": [
          "warn", {
            "vars": "local",
            "varsIgnorePattern": "^[A-Z](?:From|To)?$", // ignore type params
            "args": "none",
            "ignoreRestSiblings": false
          }
        ]
      }
    },

    // === AssemblyScript rules (extends TypeScript rules) =====================

    {
      files: [
        "**/assembly/**/*.ts",
        "src/**/*.ts",
        "lib/parse/src/**/*.ts"
      ],
      rules: {
        // Namespaces are quite useful in AssemblyScript
        "@typescript-eslint/no-namespace": "off",

        // There is actually codegen difference here
        "@typescript-eslint/no-array-constructor": "off",

        // Sometimes it can't be avoided to add a @ts-ignore
        "@typescript-eslint/ban-ts-comment": "off",

        // Utilized to achieve portability in some cases
        "@typescript-eslint/no-non-null-assertion": "off",
      }
    },

    // === Compiler rules (extends AssemblyScript rules) =======================

    {
      files: [
        "src/**/*.ts",
        "std/assembly/**/*.ts"
      ],
      rules: {
        // There is an actual codegen difference here - TODO: revisit
        "no-cond-assign": "off",

        // Not all types can be omitted in AS yet - TODO: revisit
        "@typescript-eslint/no-inferrable-types": "off",

        // Used rarely to reference internals that are not user-visible
        "@typescript-eslint/triple-slash-reference": "off",

        // The compiler has its own `Function` class for example
        "no-shadow-restricted-names": "off",
        "@typescript-eslint/ban-types": "off"
      }
    },

    // === Standard Library rules (extends AssemblyScript rules) ===============

    {
      files: [
        "std/assembly/**/*.ts"
      ],
      rules: {
        // We are implementing with --noLib, so we shadow all the time
        "no-shadow-restricted-names": "off",

        // Similarly, sometimes we need the return type to be String, not string
        "@typescript-eslint/ban-types": "off"
      }
    },

    // === Standard Definition rules (extends TypeScript rules) ================

    {
      files: [
        "std/**/*.d.ts"
      ],
      rules: {
        // Often required to achieve compatibility with TypeScript
        "@typescript-eslint/no-explicit-any": "off",

        // Interfaces can be stubs here, i.e. not yet fully implemented
        "@typescript-eslint/no-empty-interface": "off",

        // Definitions make use of `object` to model rather unusual constraints
        "@typescript-eslint/ban-types": "off"
      }
    },

    // === Compiler Definition rules (extends TypeScript rules) ================

    {
      files: [
        "./index.d.ts",
        "./index.release.d.ts",
      ],
      rules: {
        // Our definitions are complicated, and all attempts to describe them
        // as modules have failed so far. As such, we re-export namespaces.
        "@typescript-eslint/no-namespace": "off",
        "@typescript-eslint/triple-slash-reference": "off"
      }
    },

    // === Test rules (extends TypeScript rules) ===============================

    {
      files: [
        "./tests/compiler/**/*.ts",
        "./lib/loader/tests/assembly/**/*.ts"
      ],
      rules: {
        // Tests typically include unusual code patterns on purpose. This is
        // very likely not an extensive list, but covers what's there so far.
        "no-empty": "off",
        "no-cond-assign": "off",
        "no-compare-neg-zero": "off",
        "no-inner-declarations": "off",
        "no-constant-condition": "off",
        "use-isnan": "off",
        "@typescript-eslint/no-namespace": "off",
        "@typescript-eslint/no-unused-vars": "off",
        "@typescript-eslint/no-empty-function": "off",
        "@typescript-eslint/no-non-null-assertion": "off",
        "@typescript-eslint/no-extra-semi": "off",
        "@typescript-eslint/no-inferrable-types": "off",
        "@typescript-eslint/ban-types": "off",
        "@typescript-eslint/triple-slash-reference": "off",
        "@typescript-eslint/ban-ts-comment": "off",
        "@typescript-eslint/no-extra-non-null-assertion": "off",
        "@typescript-eslint/no-empty-interface": "off"
      }
    },
  ]
};


text:
body {
	background: #f9f9f9;
}

#header {
	margin: 0;
	padding: 0;
	height: 46px;
	border-bottom:#c6c6c6 1px solid;
	background: #d9d9d9; /* fallback color */
	background:-moz-linear-gradient(bottom,  #d7d7d7,  #e4e4e4);
	background:-webkit-gradient(linear, left bottom, left top, from(#d7d7d7), to(#e4e4e4));
}

#header a {
	color: #464646;
	text-decoration: none;
}

#header h1 {
	font: normal 22px Georgia, "Times New Roman", "Bitstream Charter", Times, serif;
	padding: 10px 8px 5px;
	color: #464646;
	background: transparent;
	margin: 0;
	float: left;
}

#header h1 a {
	color: #464646;
	background: transparent;
}

#header h1 a:hover {
	color: #464646;
	background: transparent;
	text-decoration:underline;
}

#navigation{
	padding: 0;
	background-color: #CCCC66;
	background: -webkit-gradient(linear, 0% 100%, 0% 0%, from(#D7D7D7), to(#E4E4E4));
	border-bottom:#c6c6c6 1px solid;
	clear: both;
	color: #333;
	overflow: auto;
}

#navigation {
	overflow: hidden;
	}

#navlist    {
	margin: 0px;
	}

#navigation ul li {
	list-style-type: none;
	line-height:32px;
	padding: 0px;
	margin: 0px;
	display: block;
	float: left;
	text-align: center;
	}

#navigation ul li a {
	color: #003d4c;
	font-weight: 100;
	text-decoration: none;
	display: block;
	line-height:32px;
	padding: 0 10px;
	}

#navigation li a.active { background: #003d4c; }
#navigation li a.active { color: #fff; }
#navigation a:hover { color: #fff; background: #003d4c; }

#content {
}

/* Admin Footer */
#footer {
	border-top: 1px;
	border-style: solid;
	color: #777;
	border-color: #d1d1d1;
	background: #d9d9d9; /* fallback color */
	background:-moz-linear-gradient(bottom,  #d7d7d7,  #e4e4e4);
	background:-webkit-gradient(linear, left bottom, left top, from(#d7d7d7), to(#e4e4e4));
}

#footer,
#footer a {
	font-size: 12px;
}

#footer p {
	margin: 0;
	padding: 15px;
	line-height: 15px;
}

#footer a {
	text-decoration: none;
}

#footer a:hover {
	text-decoration: underline;
}

form div {
	clear: none;
	margin-bottom: 0;
}

div.items {
	clear: both;
}

.btnbar { float: right; }

ul.horiz li
{
	float: left;
	display: inline;
	list-style-type: none;
	padding-right: 0px;
	padding-left: 0px;
	vertical-align: baseline;
}
ul.nav li a { display: block; padding: 0 3px 0 0;}

ul ul { position: absolute; margin: 0; padding: 0; }
ul ul li { width: 99%; display: block; border-bottom: 1px solid #CACACA; }
li ul {display: none;}
ul li:hover > ul {display: block; }

/* Example tokeninput style #1: Token vertical list*/
ul.token-input-list {
    overflow: hidden;
    height: auto !important;
    height: 1%;
    border: 1px solid #999;
    cursor: text;
    font-size: 12px;
    font-family: Verdana;
    z-index: 999;
    margin: 0;
    padding: 0;
    background-color: #fff;
}

ul.token-input-list li {
    list-style-type: none;
}

ul.token-input-list li input {
    border: 0;
    padding: 3px 8px;
    background-color: white;
}

li.token-input-token {
    overflow: hidden;
    height: auto !important;
    height: 1%;
    margin: 3px;
    padding: 3px 5px;
    background-color: #d0efa0;
    color: #000;
    font-weight: bold;
    cursor: default;
    display: block;
}

li.token-input-token p {
    float: left;
    padding: 0;
    margin: 0;
}

li.token-input-token span {
    float: right;
    color: #777;
    cursor: pointer;
}

li.token-input-selected-token {
    background-color: #08844e;
    color: #fff;
}

li.token-input-selected-token span {
    color: #bbb;
}

div.token-input-dropdown {
    position: absolute;
    width: 350px;
    background-color: #fff;
    overflow: hidden;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    cursor: default;
    font-size: 12px;
    font-family: Verdana;
    z-index: 1;
}

div.token-input-dropdown p {
    margin: 0;
    padding: 5px;
    font-weight: bold;
    color: #777;
}

div.token-input-dropdown ul {
    margin: 0;
    padding: 0;
}

div.token-input-dropdown ul li {
    background-color: #fff;
    padding: 3px;
    list-style-type: none;
}

div.token-input-dropdown ul li.token-input-dropdown-item {
    background-color: #fafafa;
}

div.token-input-dropdown ul li.token-input-dropdown-item2 {
    background-color: #fff;
}

div.token-input-dropdown ul li em {
    font-weight: bold;
    font-style: normal;
}

div.token-input-dropdown ul li.token-input-selected-dropdown-item {
    background-color: #d0efa0;
}

div.box { padding: 0; }


text:
"""Tests for plugin.py"""

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from unittest import TestCase

from IPython.core.plugin import Plugin, PluginManager

#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------

class FooPlugin(Plugin):
    pass

class BarPlugin(Plugin):
    pass

class BadPlugin(object):
    pass

class PluginTest(TestCase):

    def setUp(self):
        self.manager = PluginManager()

    def test_register_get(self):
        self.assertEquals(None, self.manager.get_plugin('foo'))
        foo = FooPlugin()
        self.manager.register_plugin('foo', foo)
        self.assertEquals(foo, self.manager.get_plugin('foo'))
        bar = BarPlugin()
        self.assertRaises(KeyError, self.manager.register_plugin, 'foo', bar)
        bad = BadPlugin()
        self.assertRaises(TypeError, self.manager.register_plugin, 'bad')

    def test_unregister(self):
        foo = FooPlugin()
        self.manager.register_plugin('foo', foo)
        self.manager.unregister_plugin('foo')
        self.assertEquals(None, self.manager.get_plugin('foo'))


text:
package ma.meditel.reporting.dao.implementations;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import ma.meditel.reporting.dao.interfaces.ITrafficPerClassDao;
import ma.meditel.reporting.entities.TrafficClassification;
import ma.meditel.reporting.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class TrafficPerClassDaoImpl implements ITrafficPerClassDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<TrafficClassification> getAllInterfaceTrafficsBetween(Long idInterface, Date startDate, Date endDate, Long classTraffic) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			Criteria cr = session.createCriteria(TrafficClassification.class);
			cr.add(Restrictions.eq("iinterface.idInterface", idInterface))
			.add(Restrictions.ge("date", startDate))
			.add(Restrictions.le("date", endDate))
			.add(Restrictions.eq("tclasse.refTClasse", classTraffic))
			.addOrder(Order.asc("date"));

			tx.commit();

			return cr.list();

		} catch (Exception e) {
			if (tx != null) tx.rollback();
			throw e;

		} finally {
			session.close();
		}
	}

	@Override
	public List<TrafficClassification> getAllInterfaceTrafficsClassificationOfTheDay(Long idInterface, Date dayDate, Long classTraffic) {
		Long HOUR = (long) (3600*1000);
		Date endDate = new Date(dayDate.getTime() + 24 * HOUR);

		return getAllInterfaceTrafficsBetween(idInterface, dayDate, endDate, classTraffic);
	}

	@Override
	public Double getMaxValueTrafficClassificationInADay(Date dayDate,
			Long idInterface, Long classification) {
		Long HOUR = (long) (3600*1000);
		Date endDate = new Date(dayDate.getTime() + 24 * HOUR);

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			Criteria cr = session.createCriteria(TrafficClassification.class);
			cr.add(Restrictions.eq("iinterface.idInterface", idInterface))
			.add(Restrictions.ge("date", dayDate))
			.add(Restrictions.le("date", endDate))
			.add(Restrictions.eq("tclasse.refTClasse", classification))
			.addOrder(Order.asc("date"))
			.setProjection(Projections.max("metriceValue"));

			tx.commit();

			return (Double) cr.uniqueResult();

		} catch (Exception e) {
			if (tx != null) tx.rollback();
			throw e;

		} finally {
			session.close();
		}
	}

	static public List<Long> displayObjectsList(List list)
    {
        Iterator iter = list.iterator();
        if (!iter.hasNext())
        {
//            System.out.println("No objects to display.");
            return null;
        }

        List<Long> listId = new ArrayList<Long>();
        while (iter.hasNext())
        {
            Object[] obj = (Object[]) iter.next();
//            for (int i=0;i<obj.length;i++)
//            {
            	listId.add((Long)obj[0]);
//            }
        }

        return listId;
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getListOfIdInterfaceInClass() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			Criteria cr = session.createCriteria(TrafficClassification.class);
			ProjectionList projList = Projections.projectionList();
			projList.add(Projections.property("iinterface.idInterface"))
			.add(Projections.groupProperty("iinterface.idInterface"));

			cr.setProjection(projList);

			tx.commit();

			List<Long> theList = displayObjectsList(cr.list());

			return theList;

		} catch (Exception e) {
			if (tx != null) tx.rollback();
			throw e;

		} finally {
			session.close();
		}
	}

}


text:
package com.wqy.ganhuo.base;

import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.wqy.ganhuo.R;
import com.wqy.ganhuo.utils.CommonUtil;

public class BaseActivity extends AppCompatActivity {

    private int screenWidth;
    private int screentHeight;
    float startX = 0;
    float distanceX = 0;
    private SystemBarTintManager systemBarTintManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        systemBarTintManager = new SystemBarTintManager(this);
        // enable status bar tint
        systemBarTintManager.setStatusBarTintEnabled(true);
        // enable navigation bar tint
        systemBarTintManager.setNavigationBarTintEnabled(true);
        systemBarTintManager.setTintResource(R.color.primaryDark);
        Point point = CommonUtil.getInstance(getApplicationContext()).getScreenSize();
        screenWidth = point.x;
        screentHeight = point.y;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}


text:
module CoinJar
  class FairRate

    attr_accessor :currency, :bid, :ask, :spot

    def initialize(currency = "USD")
      @currency = currency
      response = CoinJar.client.get("fair_rate/" + currency)
      @bid = BigDecimal.new response[:bid]
      @ask = BigDecimal.new response[:ask]
      @spot = BigDecimal.new response[:spot]
    end

  end
end


text:
const test = require('tap').test
const server = require('./../../server.js')
const findByIdMethod = require('../../../lib/methods/findByID').findByID
const sinon = require('sinon')
var ARROW
var CONNECTOR

test('### Start Arrow ###', function (t) {
  server()
    .then((inst) => {
      ARROW = inst
      CONNECTOR = ARROW.getConnector('appc.mysql')
      t.ok(ARROW, 'Arrow has been started')
      t.end()
    })
    .catch((err) => {
      t.threw(err)
    })
})

test('FindByID without primary key', sinon.test(function (t) {
  const Model = ARROW.getModel('Posts')
  function cbError (errorMessage) { }
  const cbErrorSpy = this.spy(cbError)

  const tableStub = this.stub(
    CONNECTOR,
    'getTableName',
    (Model) => {
      return 'post'
    }
  )

  const primaryKeyStub = this.stub(
    CONNECTOR,
    'getPrimaryKeyColumn',
    (Model) => {
      return false
    }
  )

  const escapeKeysStub = this.stub(
    CONNECTOR,
    'escapeKeys',
    (Model) => {
      return ['title', 'name']
    }
  )

  findByIdMethod.bind(CONNECTOR, Model, 'id', cbErrorSpy)()

  t.ok(primaryKeyStub.calledOnce)
  t.ok(tableStub.calledOnce)
  t.ok(escapeKeysStub.calledOnce)
  t.ok(cbErrorSpy.calledOnce)

  t.end()
}))

test('FindByID empty', sinon.test(function (t) {
  const Model = ARROW.getModel('Posts')
  function cb () { }
  const cbSpy = this.spy(cb)

  const tableStub = this.stub(
    CONNECTOR,
    'getTableName',
    (Model) => {
      return 'post'
    }
  )

  const primaryKeyStub = this.stub(
    CONNECTOR,
    'getPrimaryKeyColumn',
    (Model) => {
      return true
    }
  )

  const escapeKeysStub = this.stub(
    CONNECTOR,
    'escapeKeys',
    (Model) => {
      return ['title', 'name']
    }
  )

  const queryStub = this.stub(
    CONNECTOR,
    '_query',
    (query, id, callback, rows) => {
      rows()
    }
  )

  findByIdMethod.bind(CONNECTOR, Model, 'id', cbSpy)()

  t.ok(primaryKeyStub.calledOnce)
  t.ok(tableStub.calledOnce)
  t.ok(escapeKeysStub.calledOnce)
  t.ok(queryStub.calledOnce)
  t.ok(cbSpy.calledOnce)

  t.end()
}))

test('FindByID response', sinon.test(function (t) {
  const Model = ARROW.getModel('Posts')
  function cb (errorMessage, data) { }
  const cbSpy = this.spy(cb)

  const tableStub = this.stub(
    CONNECTOR,
    'getTableName',
    (Model) => {
      return 'post'
    }
  )

  const primaryKeyStub = this.stub(
    CONNECTOR,
    'getPrimaryKeyColumn',
    (Model) => {
      return true
    }
  )

  const escapeKeysStub = this.stub(
    CONNECTOR,
    'escapeKeys',
    (Model) => {
      return ['title', 'name']
    }
  )

  const getInstanceFromRowStub = this.stub(
    CONNECTOR,
    'getInstanceFromRow',
    (Model, rows) => {
      return 'data'
    }
  )

  const queryStub = this.stub(
    CONNECTOR,
    '_query',
    (query, id, callback, rows) => {
      rows('valid')
    }
  )

  findByIdMethod.bind(CONNECTOR, Model, 'id', cbSpy)()

  t.ok(primaryKeyStub.calledOnce)
  t.ok(tableStub.calledOnce)
  t.ok(escapeKeysStub.calledOnce)
  t.ok(queryStub.calledOnce)
  t.ok(getInstanceFromRowStub.calledOnce)
  t.ok(cbSpy.calledOnce)
  t.ok(cbSpy.calledWith(null, 'data'))

  t.end()
}))

test('### Stop Arrow ###', function (t) {
  ARROW.stop(function () {
    t.pass('Arrow has been stopped!')
    t.end()
  })
})