text:
module(..., package.seeall)

local counter = require("core.counter")
local lib = require("core.lib")
local lwcounter = require("apps.lwaftr.lwcounter")
local lwutil = require("apps.lwaftr.lwutil")
local shm = require("core.shm")
local top = require("program.top.top")
local engine = require("core.app")
local ps = require("program.ps.ps")

local keys, fatal = lwutil.keys, lwutil.fatal

-- Get the counter dir from the code.
local counters_dir = lwcounter.counters_dir

function show_usage (code)
   print(require("program.lwaftr.query.README_inc"))
   main.exit(code)
end

local function sort (t)
   table.sort(t)
   return t
end

local function is_counter_name (name)
   return lwcounter.counter_names[name] ~= nil
end

function parse_args (raw_args)
   local handlers = {}
   local opts = {}
   local name
   function handlers.h() show_usage(0) end
   function handlers.l ()
      for _, name in ipairs(sort(lwcounter.counter_names)) do
         print(name)
      end
      main.exit(0)
   end
   function handlers.n (arg)
      opts.name = assert(arg)
   end
   local args = lib.dogetopt(raw_args, handlers, "hln:",
                             { help="h", ["list-all"]="l", name="n" })
   if #args > 2 then show_usage(1) end
   return opts, unpack(args)
end

local function read_counters (tree)
   local ret = {}
   local cnt, cnt_path, value
   local max_width = 0
   local counters_path = "/" .. tree .. "/" .. counters_dir
   local counters = shm.children(counters_path)
   for _, name in ipairs(counters) do
      cnt_path = counters_path .. name
      cnt = counter.open(cnt_path, 'readonly')
      value = tonumber(counter.read(cnt))
      if value ~= 0 then
         name = name:gsub(".counter$", "")
         if #name > max_width then max_width = #name end
         ret[name] = value
      end
   end
   return ret, max_width
end

-- Filters often contain '-', which is a special character for match.
-- Escape it.
local function skip_counter (name, filter)
   local escaped_filter = filter
   if escaped_filter then escaped_filter = filter:gsub("-", "%%-") end
   return filter and not name:match(escaped_filter)
end

local function print_counter (name, value, max_width)
   local nspaces = max_width - #name
   print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value)))
end

local function print_counters (tree, filter)
   print("lwAFTR operational counters (non-zero)")
   -- Open, read and print whatever counters are in that directory.
   local counters, max_width = read_counters(tree)
   for _, name in ipairs(sort(keys(counters))) do
      if not skip_counter(name, filter) then
         local value = counters[name]
         print_counter(name, value, max_width)
      end
   end
end

-- Return the pid that was specified, unless it was a leader process,
-- in which case, return the follower pid that actually has useful counters.
local function pid_to_parent(pid)
   -- It's meaningless to get the parent of a nil 'pid'.
   if not pid then return pid end
   local pid = tonumber(pid)
   for _, name in ipairs(shm.children("/")) do
      local p = tonumber(name)
      if p and ps.is_worker(p) then
         local leader_pid = tonumber(ps.get_leader_pid(p))
         -- If the precomputed by-name pid is the leader pid, set the pid
         -- to be the follower's pid instead to get meaningful counters.
      if leader_pid == pid then pid = p end
      end
   end
   return pid
end

function run (raw_args)
   local opts, arg1, arg2 = parse_args(raw_args)
   local pid, counter_name
   if not opts.name then
      if arg1 then pid = pid_to_parent(arg1) end
      counter_name = arg2 -- This may be nil
   else -- by-name: arguments are shifted by 1 and no pid is specified
      counter_name = arg1
      -- Start by assuming it was run without --reconfigurable
      local programs = engine.enumerate_named_programs(opts.name)
      pid = programs[opts.name]
      if not pid then
         fatal(("Couldn't find process with name '%s'"):format(opts.name))
      end

      -- Check if it was run with --reconfigurable
      -- If it was, find the children, then find the pid of their parent.
      -- Note that this approach will break as soon as there can be multiple
      -- followers which need to have their statistics aggregated, as it will
      -- only print the statistics for one child, not for all of them.
      for _, name in ipairs(shm.children("/")) do
         local p = tonumber(name)
         if p and ps.is_worker(p) then
            local leader_pid = tonumber(ps.get_leader_pid(p))
            -- If the precomputed by-name pid is the leader pid, set the pid
            -- to be the follower's pid instead to get meaningful counters.
            if leader_pid == pid then pid = p end
         end
      end
   end
   if not pid then
      top.select_snabb_instance(pid)
      -- The following is not reached when there are multiple instances.
      fatal("Please manually specify a pid, or a name with -n name")
   end
   print_counters(pid, counter_name)
end


text:
QuickSpecBegin(SDLHMICapabilitiesSpec)

describe(@"SDLHMICapabilities struct", ^{
    __block SDLHMICapabilities *testStruct = nil;
    __block NSNumber *somePhoneCallState = @NO;
    __block NSNumber *someNavigationState = @YES;
    __block NSNumber *someVideoStreamState = @NO;
    __block NSNumber *someRemoteControlState = @YES;
    __block NSNumber *someAppServicesState = @YES;
    __block NSNumber *someDisplaysState = @YES;
    __block NSNumber *someSeatLocationState = @NO;
    __block NSNumber *someDriverDistractionState = @NO;

    context(@"when initialized with properties", ^{
        beforeEach(^{
            testStruct = [[SDLHMICapabilities alloc] init];
            testStruct.phoneCall = somePhoneCallState;
            testStruct.navigation = someNavigationState;
            testStruct.videoStreaming = someVideoStreamState;
            testStruct.remoteControl = someRemoteControlState;
            testStruct.appServices = someAppServicesState;
            testStruct.displays = someDisplaysState;
            testStruct.seatLocation = someSeatLocationState;
            testStruct.driverDistraction = someDriverDistractionState;
        });

        it(@"should properly set properties", ^{
            expect(testStruct.phoneCall).to(equal(somePhoneCallState));
            expect(testStruct.navigation).to(equal(someNavigationState));
            expect(testStruct.videoStreaming).to(equal(someVideoStreamState));
            expect(testStruct.remoteControl).to(equal(someRemoteControlState));
            expect(testStruct.appServices).to(equal(someAppServicesState));
            expect(testStruct.displays).to(equal(someDisplaysState));
            expect(testStruct.seatLocation).to(equal(someSeatLocationState));
            expect(testStruct.driverDistraction).to(equal(someDriverDistractionState));
        });
    });

    context(@"when initialized with a dictionary", ^{
        beforeEach(^{
            NSDictionary<NSString *, NSNumber *> *structInitDict = @{
                                             SDLRPCParameterNameNavigation: someNavigationState,
                                             SDLRPCParameterNamePhoneCall: somePhoneCallState,
                                             SDLRPCParameterNameVideoStreaming: someVideoStreamState,
                                             SDLRPCParameterNameRemoteControl: someRemoteControlState,
                                             SDLRPCParameterNameAppServices: someAppServicesState,
                                             SDLRPCParameterNameDisplays: someDisplaysState,
                                             SDLRPCParameterNameSeatLocation: someSeatLocationState,
                                             SDLRPCParameterNameDriverDistraction: someDriverDistractionState
                                             };

            testStruct = [[SDLHMICapabilities alloc] initWithDictionary:structInitDict];
        });

        it(@"should properly set properties", ^{
            expect(testStruct.phoneCall).to(equal(somePhoneCallState));
            expect(testStruct.navigation).to(equal(someNavigationState));
            expect(testStruct.videoStreaming).to(equal(someVideoStreamState));
            expect(testStruct.remoteControl).to(equal(someRemoteControlState));
            expect(testStruct.appServices).to(equal(someAppServicesState));
            expect(testStruct.displays).to(equal(someDisplaysState));
            expect(testStruct.seatLocation).to(equal(someSeatLocationState));
            expect(testStruct.driverDistraction).to(equal(someDriverDistractionState));
        });
    });

    context(@"when initialized", ^{
        context(@"with no parameters", ^{
            beforeEach(^{
                testStruct = [[SDLHMICapabilities alloc] init];
            });

            it(@"properties should be nil", ^{
                expect(testStruct.phoneCall).to(beNil());
                expect(testStruct.navigation).to(beNil());
                expect(testStruct.videoStreaming).to(beNil());
                expect(testStruct.remoteControl).to(beNil());
                expect(testStruct.displays).to(beNil());
                expect(testStruct.seatLocation).to(beNil());
                expect(testStruct.appServices).to(beNil());
            });
        });

        context(@"with initWithNavigation:phoneCall:videoStreaming:remoteControl:appServices:displays:seatLocation:driverDistraction:", ^{
            beforeEach(^{
                testStruct = [[SDLHMICapabilities alloc] initWithNavigation:someNavigationState phoneCall:somePhoneCallState videoStreaming:someVideoStreamState remoteControl:someRemoteControlState appServices:someAppServicesState displays:someDisplaysState seatLocation:someSeatLocationState driverDistraction:someDriverDistractionState];
            });

            it(@"properties should be nil", ^{
                expect(testStruct.phoneCall).to(equal(somePhoneCallState));
                expect(testStruct.navigation).to(equal(someNavigationState));
                expect(testStruct.videoStreaming).to(equal(someVideoStreamState));
                expect(testStruct.remoteControl).to(equal(someRemoteControlState));
                expect(testStruct.appServices).to(equal(someAppServicesState));
                expect(testStruct.displays).to(equal(someDisplaysState));
                expect(testStruct.seatLocation).to(equal(someSeatLocationState));
                expect(testStruct.driverDistraction).to(equal(someDriverDistractionState));
            });
        });
    });
});

QuickSpecEnd

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable no-new */
import Popup from './popup'
import { document } from './../globals'

const $templates = document.getElementById('iframe-templates')
const $main = document.querySelector('main')
const $modes = {
  smart: document.getElementById('mode-smart'),
  date: document.getElementById('mode-date'),
  active: document.getElementById('mode-active')
}
const $settings = {
  tab: document.getElementById('settings-tab'),
  sync: document.getElementById('settings-sync')
}

new Popup($templates, $main, $modes, $settings)


text:
namespace {
// URL to launch Castv2Player_Staging app on Chromecast
const char kCastAppPresentationUrl[] =
    "https://google.com/cast#__castAppId__=BE6E4473/"
    "__castClientId__=143692175507258981";
const char kVideo[] = "video";
const char kBearVP9Video[] = "bear-vp9-opus.webm";
const char kPlayer[] = "player.html";
const char kOriginUrl[] = "http://origin/";
}  // namespace

namespace media_router {

MediaRouterE2EBrowserTest::MediaRouterE2EBrowserTest()
    : media_router_(nullptr) {
}

MediaRouterE2EBrowserTest::~MediaRouterE2EBrowserTest() {
}

void MediaRouterE2EBrowserTest::SetUpOnMainThread() {
  MediaRouterBaseBrowserTest::SetUpOnMainThread();
  media_router_ =
      MediaRouterFactory::GetApiForBrowserContext(browser()->profile());
  DCHECK(media_router_);
}

void MediaRouterE2EBrowserTest::TearDownOnMainThread() {
  observer_.reset();
  route_id_.clear();
  media_router_ = nullptr;
  MediaRouterBaseBrowserTest::TearDownOnMainThread();
}

void MediaRouterE2EBrowserTest::OnRouteResponseReceived(
    const RouteRequestResult& result) {
  ASSERT_TRUE(result.route());
  route_id_ = result.route()->media_route_id();
}

void MediaRouterE2EBrowserTest::CreateMediaRoute(
    const MediaSource& source,
    const GURL& origin,
    content::WebContents* web_contents) {
  DCHECK(media_router_);
  observer_.reset(new TestMediaSinksObserver(media_router_, source, origin));
  observer_->Init();

  DVLOG(1) << "Receiver name: " << receiver();
  // Wait for MediaSinks compatible with |source| to be discovered.
  ASSERT_TRUE(ConditionalWait(
      base::TimeDelta::FromSeconds(30), base::TimeDelta::FromSeconds(1),
      base::Bind(&MediaRouterE2EBrowserTest::IsSinkDiscovered,
                 base::Unretained(this))));

  const auto& sink_map = observer_->sink_map;
  const auto it = sink_map.find(receiver());
  const MediaSink& sink = it->second;

  // The callback will set route_id_ when invoked.
  std::vector<MediaRouteResponseCallback> route_response_callbacks;
  route_response_callbacks.push_back(
      base::Bind(&MediaRouterE2EBrowserTest::OnRouteResponseReceived,
                 base::Unretained(this)));
  media_router_->CreateRoute(source.id(), sink.id(), origin, web_contents,
                             route_response_callbacks, base::TimeDelta(),
                             is_off_the_record());

  // Wait for the route request to be fulfilled (and route to be started).
  ASSERT_TRUE(ConditionalWait(
      base::TimeDelta::FromSeconds(30), base::TimeDelta::FromSeconds(1),
      base::Bind(&MediaRouterE2EBrowserTest::IsRouteCreated,
                 base::Unretained(this))));
}

void MediaRouterE2EBrowserTest::StopMediaRoute() {
  ASSERT_FALSE(route_id_.empty());
  media_router_->TerminateRoute(route_id_);
}

bool MediaRouterE2EBrowserTest::IsSinkDiscovered() const {
  return ContainsKey(observer_->sink_map, receiver());
}

bool MediaRouterE2EBrowserTest::IsRouteCreated() const {
  return !route_id_.empty();
}

void MediaRouterE2EBrowserTest::OpenMediaPage() {
  base::StringPairs query_params;
  query_params.push_back(std::make_pair(kVideo, kBearVP9Video));
  std::string query = media::GetURLQueryString(query_params);
  GURL gurl = content::GetFileUrlWithQuery(media::GetTestDataFilePath(kPlayer),
                                           query);
  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
        browser(), gurl, 1);
}

// Test cases

IN_PROC_BROWSER_TEST_F(MediaRouterE2EBrowserTest, MANUAL_TabMirroring) {
  EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
  EXPECT_EQ(1, browser()->tab_strip_model()->count());

  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
      browser(), GURL("about:blank"), 1);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = SessionTabHelper::IdForTab(web_contents);

  // Wait for 30 seconds to make sure the route is stable.
  CreateMediaRoute(
      MediaSourceForTab(tab_id), GURL(kOriginUrl), web_contents);
  Wait(base::TimeDelta::FromSeconds(30));

  // Wait for 10 seconds to make sure route has been stopped.
  StopMediaRoute();
  Wait(base::TimeDelta::FromSeconds(10));
}

IN_PROC_BROWSER_TEST_F(MediaRouterE2EBrowserTest, MANUAL_CastApp) {
  // Wait for 30 seconds to make sure the route is stable.
  CreateMediaRoute(MediaSourceForPresentationUrl(kCastAppPresentationUrl),
                   GURL(kOriginUrl), nullptr);
  Wait(base::TimeDelta::FromSeconds(30));

  // Wait for 10 seconds to make sure route has been stopped.
  StopMediaRoute();
  Wait(base::TimeDelta::FromSeconds(10));
}

}  // namespace media_router


text:
<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\database\Content as ContentModel;

/**
 * Content represents the model behind the search form about `common\models\database\Content`.
 */
class Content extends ContentModel
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'updated_at', 'created_at'], 'integer'],
            [['title', 'description', 'img'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ContentModel::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'updated_at' => $this->updated_at,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'img', $this->img]);

        return $dataProvider;
    }
}


text:
@todo http://www.justinappears.com/blog/2-no-downtime-deploys-with-unicorn/ (no downtime deployment & rolling )

run demonized with configuration file under rbenv

```bash
# ~/apps/your_rails_app/
RAILS_ENV=staging rbenv exec unicorn -c config/unicorn.rb -D
```

### Unicorn config

```ruby
# config/unicorn.rb

working_directory "/var/www/your_rails_app"
pid "/var/www/your_rails_app/current_hack/tmp/pids/unicorn.pid"
stderr_path "/var/www/your_rails_app/log/unicorn.log"
stdout_path "/var/www/your_rails_app/log/unicorn.log"

listen '/tmp/unicorn.your_rails_app.sock' # this is the socket that will be picked up by NgineX
worker_processes 2 # specifies the maximum number of seconds
                   # a worker can take to respond to a request before the
                   # master kills it and forks a new one
timeout 30
```

Note: I know lot of developers prefer to use `/home/deploy/apps/your_rails_app` directory but generally,
web apps are stored inside `/var/www` on Unix since the `/var` directory is designated for files that
increase in size over time, which is the case with most web apps.

* https://github.com/blog/517-unicorn
* http://vladigleba.com/blog/2014/03/21/deploying-rails-apps-part-3-configuring-unicor/
* http://railscasts.com/episodes/293-nginx-unicorn

# unicorn init.d

https://github.com/railscasts/335-deploying-to-a-vps/blob/master/blog-nginx/config/unicorn_init.sh

# unicorn start/stop

    # demon
    /etc/init.d/unicorn_myapp restart

    # restart pid process
    kill -USR2 unicorn_master_pid;

    # reexecute unicorn master process, takes more time but reload most of the stuff
    kill -USR2 unicorn_master_pid; kill -QUIT unicorn_master_pid

http://stackoverflow.com/questions/19896800/starting-or-restarting-unicorn-with-capistrano-3-x

super kill

    sudo kill `cat /home/deploy/apps/my_project/current/tmp/pids/unicorn.pid`

    ps aux | grep unicorn

## real life example of unicorn init.d

```
# /etc/init.d/unicorn_myapp
#!/bin/sh
### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Manage unicorn server
# Description:       Start, stop, restart unicorn server for a specific application.
### END INIT INFO

# Exit script if any statement returns a non-true return value
set -e

# Feel free to change any of the following variables for your app:
TIMEOUT=${TIMEOUT-60}
APP_ROOT=/home/deploy/apps/myapp/current
PID=/var/run/unicorn.myapp.pid

CMD="cd /home/deploy/apps/myapp/current; bundle exec unicorn -D -c /home/deploy/apps/myapp/config/unicorn.conf.rb -E staging"
AS_USER=deploy

# Exit script if you try to use an uninitialised variable
set -u

OLD_PIN="$PID.oldbin"

sig () {
  test -s "$PID" && kill -$1 `cat $PID`
}

oldsig () {
  test -s $OLD_PIN && kill -$1 `cat $OLD_PIN`
}

run () {
  if [ "$(id -un)" = "$AS_USER" ]; then
    eval $1
  else
    su -c "$1" - $AS_USER
  fi
}

case "$1" in
start)
  sig 0 && echo >&2 "Already running" && exit 0
  run "$CMD"
  ;;
stop)
  sig QUIT && exit 0
  echo >&2 "Not running"
  ;;
force-stop)
  sig TERM && exit 0
  echo >&2 "Not running"
  ;;
restart|reload)
  sig USR2 && echo reloaded OK && exit 0
  echo >&2 "Couldn't reload, starting '$CMD' instead"
  run "$CMD"
  ;;
upgrade)
  if sig USR2 && sleep 2 && sig 0 && oldsig QUIT
  then
    n=$TIMEOUT
    while test -s $OLD_PIN && test $n -ge 0
    do
      printf '.' && sleep 1 && n=$(( $n - 1 ))
    done
    echo

    if test $n -lt 0 && test -s $OLD_PIN
    then
      echo >&2 "$OLD_PIN still exists after $TIMEOUT seconds"
      exit 1
    fi
    exit 0
  fi
  echo >&2 "Couldn't upgrade, starting '$CMD' instead"
  run "$CMD"
  ;;
reopen-logs)
  sig USR1
  ;;
*)
  echo >&2 "Usage: $0 <start|stop|restart|upgrade|force-stop|reopen-logs>"
  exit 1
  ;;
esac
```

## real life example of unicorn.conf

```
# /home/deploy/apps/myapp/config/unicorn.conf.rb

# Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.

# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 3

# Since Unicorn is never exposed to outside clients, it does not need to
# run on the standard HTTP port (80), there is no reason to start
Unicorn
# as root unless it's from system init scripts.
# If running the master process as root and the workers as an
unprivileged
# user, do this to switch euid/egid in the workers (also chowns logs):
# user "unprivileged_user", "unprivileged_group"

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory "/home/deploy/apps/myapp/current"

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
listen "/var/run/unicorn.myapp.sock", :backlog => 64
listen 8080, :tcp_nopush => true

# nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 30

# feel free to point this anywhere accessible on the filesystem
#pid "/path/to/app/shared/pids/unicorn.pid"
pid "/var/run/unicorn.myapp.pid"

# By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
stderr_path "/var/log/unicorn.stderr.log"
stdout_path "/var/log/unicorn.stdout.log"

# combine Ruby 2.0.0dev or REE with "preload_app true" for memory
savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

# Enable this flag to have unicorn test client connections by writing
the
# beginning of the HTTP headers before calling the application. This
# prevents calling the application for connections that have
disconnected
# while queued. This is only guaranteed to detect clients on the same
# host unicorn runs on, and unlikely to detect disconnects even on a
# fast LAN.
check_client_connection false

before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!

  # The following is only recommended for memory/DB-constrained
  # installations. It is not needed if your system can house
  # twice as many worker_processes as you have configured.
  #
  # # This allows a new master process to incrementally
  # # phase out the old master process with SIGTTOU to avoid a
  # # thundering herd (especially in the "preload_app false" case)
  # # when doing a transparent upgrade. The last worker spawned
  # # will then kill off the old master process with a SIGQUIT.
  old_pid = "#{server.config[:pid]}.oldbin"
  if old_pid != server.pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end

  # Throttle the master from forking too quickly by sleeping. Due
  # to the implementation of standard Unix signal handlers, this
  # helps (but does not completely) prevent identical, repeated signals
  # from being lost when the receiving process is busy.
  sleep 1
end

after_fork do |server, worker|
  # per-process listener ports for debugging/admin/migrations
  # addr = "127.0.0.1:#{9293 + worker.nr}"
  # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)

  # the following is *required* for Rails + "preload_app true",
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection

  # if preload_app is true, then you may also want to check and
  # restart any other shared sockets/descriptors such as Memcached,
  # and Redis. TokyoCabinet file handles are safe to reuse
  # between any number of forked children (assuming your kernel
  # correctly implements pread()/pwrite() system calls)
end
```


text:
"""
This file is part of RT1.
(c) 2016- Raphael Quast
For COPYING and LICENSE details, please refer to the LICENSE file
"""

from setuptools import setup, find_packages
#from setuptools import find_packages
from rt1 import __version__

setup(name='rt1',

      version=__version__,

      description='RT1 - bistatic single scattering radiative transfer model',

      packages=find_packages(),  # ['rt1'],
      package_dir={'rt1': 'rt1'},
      include_package_data=False,

      author="Raphael Quast",
      author_email='raphael.quast@geo.tuwien.ac.at',
      maintainer='Raphael Quast',
      maintainer_email='raphael.quast@geo.tuwien.ac.at',

      #~ license='APACHE 2',

      url='https://github.com/TUW-GEO/rt1',

      long_description=('A module to perform forward-simulation and ' +
                        'parameter-inversion of incidence-angle dependent ' +
                        'backscatter observations based on a first-order ' +
                        'radiative-transfer model describing a rough surface' +
                        'covered by a homogeneous layer of scattering' +
                        'media.'),

      install_requires=["numpy>=1.16", "sympy>=1.4", "scipy>=1.2",
                        "pandas>=0.24", "matplotlib>=3.0"],
      extras_require={'full' : ["symengine>=0.4", "xarray>=0.16"]},

      keywords=["physics", "radiative transfer"],

      # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=[
          'Intended Audience :: Science/Research',
          'Topic :: Scientific/Engineering :: Atmospheric Science',

          # Pick your license as you wish (should match "license" above)
          #~ 'License :: OSI Approved :: MIT License',

          'Programming Language :: Python :: 3.7'
      ],

      )


text:
<?php namespace Krucas\Permission\Factory;

use Krucas\Permission\Validator\ValidatorInterface;

class ValidatorFactory implements ValidatorFactoryInterface
{
    /**
     * Create validator from given class.
     *
     * @param string $class Class name to create.
     * @return \Krucas\Permission\Validator\ValidatorInterface
     */
    public function make($class)
    {
        if (strlen($class) <= 0) {
            throw new \InvalidArgumentException('Failed to resolve validator for empty class!');
        }

        $validator = $this->instantiateClass($class);

        if ($validator instanceof ValidatorInterface) {
            return $validator;
        }

        throw new \InvalidArgumentException('Resolved class [' . get_class($validator) . '] is not validator!');
    }

    /**
     * Instantiate new object of given class.
     *
     * @param string $class Class to instantiate.
     * @return \object
     */
    protected function instantiateClass($class)
    {
        return new $class();
    }
}


text:
{% extends "profile_base.html" %}

{% load i18n %}

{% block blog_tab_class %} ui-tabs-selected ui-state-active{% endblock %}

{% block right_block_outer %}{% endblock %}
{% block center_class%}full_width{% endblock %}
{% block body_content %}

        {% if request.user == current_user %}
            {% trans %}Write post{% endtrans %}
        {% endif %}
        {% trans %}Posts{% endtrans %}
        {% trans %}Posts (compact view){% endtrans %}

    {% block tab_content %}{% endblock %}
{% endblock %}


text:
package org.ovirt.engine.core.bll.storage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.ImportVmCommand;
import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters;
import org.ovirt.engine.core.common.vdscommands.GetVmsInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.utils.ovf.OvfManager;
import org.ovirt.engine.core.utils.ovf.OvfReaderException;

public class GetVmsFromExportDomainQuery<P extends GetAllFromExportDomainQueryParameters>
        extends QueriesCommandBase<P> {
    public GetVmsFromExportDomainQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        storage_domain_static storage = DbFacade.getInstance().getStorageDomainStaticDAO().get(
                getParameters().getStorageDomainId());
        if (storage.getstorage_domain_type() == StorageDomainType.ImportExport) {
            VDSReturnValue retVal = ExecuteVerb();
            BuildOvfReturnValue(retVal.getReturnValue());
        } else {
            getQueryReturnValue().setReturnValue(new java.util.ArrayList<VM>());
        }
    }

    protected VDSReturnValue ExecuteVerb() {
        GetVmsInfoVDSCommandParameters tempVar = new GetVmsInfoVDSCommandParameters(
                getParameters().getStoragePoolId());
        tempVar.setStorageDomainId(getParameters().getStorageDomainId());
        tempVar.setVmIdList(getParameters().getIds());
        VDSReturnValue retVal = Backend.getInstance().getResourceManager()
                .RunVdsCommand(VDSCommandType.GetVmsInfo, tempVar);
        return retVal;
    }

    protected boolean IsValidExportDomain() {
        storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(
                getParameters().getStorageDomainId(),
                getParameters().getStoragePoolId());
        if (domain != null && domain.getstorage_domain_type() == StorageDomainType.ImportExport) {
            return true;
        }
        return false;
    }

    protected void BuildOvfReturnValue(Object obj) {
        boolean shouldAdd = true;
        ArrayList<String> ovfList = (ArrayList<String>) obj;
        OvfManager ovfManager = new OvfManager();
        ArrayList<VM> vms = new ArrayList<VM>();
        List<VM> existsVms = DbFacade.getInstance().getVmDAO().getAll();
        java.util.HashMap<Guid, VM> existsVmDictionary = new java.util.HashMap<Guid, VM>();
        for (VM vm : existsVms) {
            existsVmDictionary.put(vm.getId(), vm);
        }

        if (IsValidExportDomain()) {
            VM vm = null;
            for (String ovf : ovfList) {
                try {
                    if (!ovfManager.IsOvfTemplate(ovf)) {
                        vm = new VM();
                        ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>();
                        ArrayList<VmNetworkInterface> interfaces  = new ArrayList<VmNetworkInterface>();
                        ovfManager.ImportVm(ovf, vm, diskImages, interfaces);

                        shouldAdd = getParameters().getGetAll() ? shouldAdd : !existsVmDictionary
                                .containsKey(vm.getId());

                        if (shouldAdd) {
                            // add images
                            vm.setImages(diskImages);
                            // add interfaces
                            vm.setInterfaces(interfaces);

                            // add disk map
                            Map<Guid, List<DiskImage>> images = ImportVmCommand
                                    .GetImagesLeaf(diskImages);
                            for (Guid id : images.keySet()) {
                                List<DiskImage> list = images.get(id);
                                vm.getDiskMap().put(id, list.get(list.size() - 1));
                            }
                            vms.add(vm);
                        }
                    }
                } catch (OvfReaderException ex) {
                    AuditLogableBase logable = new AuditLogableBase();
                    logable.AddCustomValue("ImportedVmName", ex.getName());
                    AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_FAILED_TO_IMPORT_VM);
                } catch (RuntimeException ex) {
                    AuditLogableBase logable = new AuditLogableBase();
                    logable.AddCustomValue("ImportedVmName", "[Unknown name]");
                    AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_FAILED_TO_IMPORT_VM);
                }
            }
        }

        getQueryReturnValue().setReturnValue(vms);
    }
}


text:
SYNONYM

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

#### Published in
Notul. syst. Inst. cryptog. Horti bot. petropol. 13: 134 (1960)

#### Original name
Mycocladus altaini S.A. Kulik, 1960

### Remarks
null


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Rocket : MonoBehaviour
{
    public float lifetime = 5.0f;
    public GameObject explosion;        // instanced explosion
    private float damage;               // damage bullet applies to a target
    //private float maxHits;              // number of collisions before bullet gets destroyed
    private float impactForce;          // force applied to a rigid body object
    private float maxInaccuracy;        // maximum amount of inaccuracy
    private float variableInaccuracy;   // used in machineguns to decrease accuracy if maintaining fire
    private float speed;                // bullet speed
    private string ownersName = "";     // name of player that launched missle

    private float framesTillRedirect = 0.0f;  // time till rocket picks a new random flight path

    private Vector3 velocity = Vector3.zero; // bullet velocity
    private Vector3 newPos = Vector3.zero;   // bullet's new position
    private Vector3 direction;               // direction bullet is travelling

    private string[] rocketInfo = new string[2];

    public void SetUp(float[] info)
    {
        damage = info[0];
        impactForce = info[1];
        //maxHits = info[2];
        maxInaccuracy = info[3];
        variableInaccuracy = info[4];
        speed = info[5];

        direction = transform.TransformDirection(Random.Range(-maxInaccuracy, maxInaccuracy) * variableInaccuracy, Random.Range(-maxInaccuracy, maxInaccuracy) * variableInaccuracy, 1);

        newPos = transform.position;
        velocity = speed * transform.forward;

        // schedule for destruction if bullet never hits anything
        Invoke("Kill", lifetime);
    }

    void Update()
    {
        if (Time.time >= framesTillRedirect)
        {
            direction = transform.TransformDirection(Random.Range(-maxInaccuracy, maxInaccuracy) * variableInaccuracy, Random.Range(-maxInaccuracy, maxInaccuracy) * variableInaccuracy, 1);
            framesTillRedirect = Time.time + Random.Range(10, 50);
        }

        // assume we move all the way
        newPos += (velocity + direction) * Time.deltaTime;

        transform.position = newPos;
    }

    void OnCollisionEnter(Collision collision)
    {
        // Instantiate explosion at the impact point and rotate the explosion
        // so that the y-axis faces along the surface normal
        ContactPoint contact = collision.contacts[0];
        Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
        Instantiate(explosion, contact.point, rotation);

        rocketInfo[0] = ownersName;
        rocketInfo[1] = damage.ToString();

        collision.collider.SendMessageUpwards("ImHit", rocketInfo, SendMessageOptions.DontRequireReceiver);

        if (collision.rigidbody)
        {
            collision.rigidbody.AddForce(transform.forward * impactForce, ForceMode.Impulse);
        }

        // And kill our selves
        Kill();
    }

    void Kill()
    {
        // Stop emitting particles in any children
        ParticleEmitter emitter = (ParticleEmitter)GetComponentInChildren<ParticleEmitter>();
        if (emitter)
            emitter.emit = false;

        // Detach children - We do this to detach the trail rendererer which should be set up to auto destruct
        transform.DetachChildren();

        // Destroy the projectile
        Destroy(gameObject);
    }

    public void setPlayer(string pName)
    {
        ownersName = pName;
        Debug.Log(ownersName + " owns this Rocket-  Send via setLauncher function");
    }
}


text:
select _id,
	st_asgeojson(location_pref)::json as location,
	st_distance(st_transform(location_pref, 25830), st_transform(st_geomfromtext($1, 4258), 25830)) as distancia
from usuarios
where st_distance(st_transform(location_pref, 25830), st_transform(st_geomfromtext($1, 4258), 25830)) < distancia_aviso and _id <> $2


text:
class SetName < Message
  attr_reader :name

  def initialize(name , options = {})
    super options
    @name = name
  end
end


text:
rec_f :: (Eq a, Integral a) => a -> a
rec_f n
  | n <= 0    = error "the input number must be positive."
  | n <= 3    = n
  | otherwise = rec_f (n - 1) +
                rec_f (n - 2) * 2 +
                rec_f (n - 3) * 3

-- Iterative process
itr_f :: (Eq a, Integral a) => a -> a
itr_f n =
  if n <= 0
  then error "the input number must be positive."
  else
    let itr_f_tmp a b c 1 = c
        itr_f_tmp a b c count =
          itr_f_tmp (a + (b * 2) + (c * 3)) a b (count - 1)
    in itr_f_tmp 3 2 1 n

-- The iterative process and the recursive process return the same result
-- in case the input parameter is integer. In other word, they return
-- different results when the input parameter @n is not an integer.


text:
--[[
title: NPL web framework connectionManager
author: links
date: 2017/3/6
]]

local connectionManager = commonlib.gettable("nwf.modules.db_postgres.connectionManager");
local dbConfig = commonlib.gettable("nwf.modules.db_postgres.config");

local driver = require("luasql.postgres");
local env;

function connectionManager.getConnection()
    if (not env) then
        env = driver.postgres();
    end
    local conn = env:connect(dbConfig.database, dbConfig.user_name, dbConfig.user_password, dbConfig.host, dbConfig.port);
    conn:setautocommit(false);
    return conn;
end

function connectionManager.releaseConnection(conn)
    if (conn:close()) then
    end
end


text:
define([ 'app/odlChat/odlChat.module' ], function(odlChatApp) {

  odlChatApp.register.factory('$odlChat', function($http, ENV) {

    var createStream = function(streamName, callback) {
      var request = {
        method : 'GET',
        url : [ service.base, 'streams/stream/', streamName ].join('')
      };
      $http(request).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        // console.log(JSON.stringify(response));
        console.log(response.headers('Location'));
        callback(response.headers('Location'))
      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.error(JSON.stringify(response));
        callback();
      });
    };

    var service = {
      base : ENV.getBaseURL("MD_SAL") + "/restconf/",

    };

    service.getMwtnWebSocketUrl = function() {
      var user = 'admin'; // TODO avoid hardcoded user/pw
      var pw = 'admin';
      var url = ENV.getBaseURL('MD_SAL'); // http://192.168.2.114:8181/
      url = url.replace('http://', 'ws://' + user + ':' + pw + '@');
      url = url.replace(':8181', ':8085/websocket');   // 'ws://admin:admin@localhost:8085/websocket'
      console.info(url);
      return url;
    };

    service.getData = function(event, callback) {

      var request = {
        method : 'GET',
        url : [ service.base,
            'config/opendaylight-inventory:nodes/' ].join('')
      };
      $http(request).then(function successCallback(response) {

        // this callback will be called asynchronously
        // when the response is available
        if (event.data.indexOf("AttributeValueChangedNotification") != -1){
        var x2js = new X2JS();
        var jsonObj = x2js.xml_str2json( event.data);
        var objId =  jsonObj.AttributeValueChangedNotification.objectId;
        var attrName =  jsonObj.AttributeValueChangedNotification.attributeName;
        var modValue =  jsonObj.AttributeValueChangedNotification.newValue;
        var notifMsg = "Object Modified: " + objId + " --- For Attribute: " + attrName + " --- With New Value As: " + modValue ;

        tweet = {
          notifType : "AttributeValueChangedNotification",
          nodeName : jsonObj.AttributeValueChangedNotification.nodeName,
          message: event.data,
          msgStr: notifMsg,
          time : JSON.stringify(new Date()).split('T')[1].substring(0, 5)
        };
      };

  if (event.data.indexOf("ProblemNotification") != -1){
        var x2js = new X2JS();
        var jsonObj = x2js.xml_str2json( event.data);
        var objId =  jsonObj.ProblemNotification.objectId;
        var problem =  jsonObj.ProblemNotification.problem;
        var severity =  jsonObj.ProblemNotification.severity;
        var notifMsg = "Object Affected: " + objId + " --- Having Problem: " + problem + " --- With Severity As: " + severity ;

        tweet = {
          notifType : "ProblemNotification",
          nodeName : jsonObj.ProblemNotification.nodeName,
          message: event.data,
          msgStr: notifMsg,
          time : JSON.stringify(new Date()).split('T')[1].substring(0, 5)
        };
      };

  if (event.data.indexOf("ObjectCreationNotification") != -1){
        var x2js = new X2JS();
        var jsonObj = x2js.xml_str2json( event.data);
        var objId =  jsonObj.ObjectCreationNotification.objectId;
        var notifMsg = "Object Created: " + objId ;

        tweet = {
          notifType : "ObjectCreationNotification",
          nodeName : jsonObj.ObjectCreationNotification.nodeName,
          message: event.data,
          msgStr: notifMsg,
          time : JSON.stringify(new Date()).split('T')[1].substring(0, 5)
        };
      };

  if (event.data.indexOf("ObjectDeletionNotification") != -1){
        var x2js = new X2JS();
        var jsonObj = x2js.xml_str2json( event.data);
        var objId =  jsonObj.ObjectDeletionNotification.objectId;
        var notifMsg = "Object Deletion: " + objId ;

        tweet = {
          notifType : "ObjectDeletionNotification",
          nodeName : jsonObj.ObjectDeletionNotification.nodeName,
          message: event.data,
          msgStr: notifMsg,
          time : JSON.stringify(new Date()).split('T')[1].substring(0, 5)
        };
      };

        callback('', tweet);
      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.error(JSON.stringify(response));
        callback('ERROR while sending ;(');
      });

    };

    service.register = function(path, callback) {
      var request = {
        method : 'POST',
        url : [ service.base,
            'operations/sal-remote:create-data-change-event-subscription' ]
            .join(''),
        data : {
          "input" : {
            "path" : path,
            "sal-remote-augment:datastore" : "CONFIGURATION",
            "sal-remote-augment:scope" : "SUBTREE"
          }
        }
      };
      $http(request).then(
          function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available
            // console.log(JSON.stringify(response));
            createStream(response.data.output['stream-name'], function(
                socketLocation) {
              callback(socketLocation);
            });
          }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.error(JSON.stringify(response));
          });
    };

    service.send = function(chat, callback) {
      var request = {
        method : 'PUT',
        url : [ service.base,
            'config/opendaylight-inventory:nodes/node/odlChat' ].join(''),
        data : {
          "node" : [ {
            "id" : "odlChat",
            "flow-node-inventory:manufacturer" : chat.nickname,
            "flow-node-inventory:software" : "",
            "flow-node-inventory:serial-number" : "",
            "flow-node-inventory:hardware" : "",
            "flow-node-inventory:description" : chat.message
          } ]
        }
      };
      $http(request).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        // console.log(JSON.stringify(response));
        callback('');

      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.error(response);
        callback('ERROR while sending ;(');
      });
    };
    return service;
  });
});


text:
importScripts('../../node_modules/steal-es6-module-loader/dist/es6-module-loader.js',
              '../../dist/system.js');

System.baseURL = '../';
System.paths['babel'] = '../node_modules/babel-core/browser.js';

System.transpiler = 'babel';

System.import('tests/es6-and-amd').then(function(m) {
  postMessage({
    amd: m.amd_module,
    es6: m.es6_module
  });
}, function(err) {
  console.error(err);
});


text:
from .common import *

class TestSign(OssTestCase):
    def test_sign_v1_x_oss_date(self):
        headers = dict()
        content = 'test example'
        put_result = self.bucket.put_object('testexampleobject.txt', content, headers=headers)
        self.assertEqual(200, put_result.status)

        headers['x-oss-date'] = oss2.utils.http_date(int(time.time()) + 24 * 60 * 60)
        try:
            self.bucket.list_objects('oss', '/', '', 10, headers=headers)
        except oss2.exceptions.ServerError as e:
            self.assertEqual(e.status, 403)
            self.assertEqual(e.message, 'The difference between the request time and the current time is too large.')

        headers['x-oss-date'] = oss2.utils.http_date(int(time.time()) + 60)
        get_result = self.bucket.get_object('testexampleobject.txt', headers=headers)
        self.assertEqual(200, get_result.status)

    def test_sign_v1_x_oss_date_url(self):
        auth = oss2.Auth(OSS_ID, OSS_SECRET)
        dest_bucket_name = self.OSS_BUCKET + "-sign-v1-url"
        dest_bucket = oss2.Bucket(auth, OSS_ENDPOINT, dest_bucket_name)
        dest_bucket.create_bucket()
        key = 'testexampleobject.txt'
        headers = dict()
        content = 'test example'
        url = dest_bucket.sign_url('PUT', key, 1650801600, headers=headers)
        print(url)

        put_result = dest_bucket.put_object_with_url(url, content)
        self.assertEqual(200, put_result.status)

        headers['x-oss-date'] = oss2.utils.http_date(int(time.time()) + 24 * 60 * 60)
        try:
            dest_bucket.get_object(key, headers=headers)
        except oss2.exceptions.ServerError as e:
            self.assertEqual(e.status, 403)
            self.assertEqual(e.message, 'The difference between the request time and the current time is too large.')

        dest_bucket.delete_object(key)
        dest_bucket.delete_bucket()

    def test_sign_v2_x_oss_date(self):
        auth = oss2.AuthV2(OSS_ID, OSS_SECRET)
        dest_bucket_name = self.OSS_BUCKET + "-sign-v2"
        dest_bucket = oss2.Bucket(auth, OSS_ENDPOINT, dest_bucket_name)
        dest_bucket.create_bucket()
        key = 'testexampleobject.txt'

        headers = dict()
        content = 'test example'
        put_result = dest_bucket.put_object(key, content, headers=headers)
        self.assertEqual(200, put_result.status)

        headers['x-oss-date'] = oss2.utils.http_date(int(time.time()) - 24 * 60 * 60)
        try:
            dest_bucket.list_objects('oss', '/', '', 10, headers=headers)
        except oss2.exceptions.ServerError as e:
            self.assertEqual(e.status, 403)
            self.assertEqual(e.message, 'The difference between the request time and the current time is too large.')

        dest_bucket.delete_object(key)
        dest_bucket.delete_bucket()

    def test_sign_v2_x_oss_date_url(self):
        auth = oss2.AuthV2(OSS_ID, OSS_SECRET)
        dest_bucket_name = self.OSS_BUCKET + "-sign-v2-url"
        dest_bucket = oss2.Bucket(auth, OSS_ENDPOINT, dest_bucket_name)
        dest_bucket.create_bucket()
        key = 'testexampleobject.txt'
        headers = dict()
        content = 'test example'
        url = dest_bucket.sign_url('PUT', key, 1650801600, headers=headers)
        print(url)

        put_result = dest_bucket.put_object_with_url(url, content)
        self.assertEqual(200, put_result.status)

        headers['x-oss-date'] = oss2.utils.http_date(int(time.time()) + 24 * 60 * 60)
        try:
            dest_bucket.get_object(key, headers=headers)
        except oss2.exceptions.ServerError as e:
            self.assertEqual(e.status, 403)
            self.assertEqual(e.message, 'The difference between the request time and the current time is too large.')

        dest_bucket.delete_object(key)
        dest_bucket.delete_bucket()

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


text:
import chainerx
from chainerx import _docs

def _set_docs_backend():
    Backend = chainerx.Backend

    _docs.set_doc(
        Backend,
        """Pluggable entity that abstracts various computing platforms.

A backend holds one or more :class:`~chainerx.Device`\\ s, each of which
represents a physical computing unit.
""")

    _docs.set_doc(
        Backend.name,
        """Backend name.

Returns:
    str: Backend name.
""")

    _docs.set_doc(
        Backend.context,
        """Context to which this backend belongs.

Returns:
    ~chainerx.Context: Context object.

""")

    _docs.set_doc(
        Backend.get_device,
        """get_device(index)
Returns a device specified by the given index.

Args:
    index (int): Device index.

Returns:
    ~chainerx.Device: Device object.
""")

    _docs.set_doc(
        Backend.get_device_count,
        """get_device_count()
Returns the number of devices available in this backend.

Returns:
    int: Number of devices.
""")

def set_docs():
    _set_docs_backend()

    _docs.set_doc(
        chainerx.get_backend,
        """get_backend(backend_name)
Returns a backend specified by the name.

Args:
    backend_name (str): Backend name.

Returns:
    ~chainerx.Backend: Backend object.
""")


text:
package clearbit_test

import (
	"fmt"

	"github.com/f2prateek/clearbit-go"
)

func ExampleCombined() {
	c := clearbit.New("93281a7c96132e8503acc84467be8c62")

	combined, err := c.Enrichment().Combined("prateek@segment.com")
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(*combined.Person.Name.FullName)
	fmt.Println(*combined.Company.Name)

	// Output:
	// Prateek Srivastava
	// Segment
}

func ExampleCombinedWithoutCompany() {
	c := clearbit.New("93281a7c96132e8503acc84467be8c62")

	combined, err := c.Enrichment().Combined("f2prateek@gmail.com")
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(*combined.Person.Name.FullName)

	// Output:
	// Prateek Srivastava
}


text:
Trendy Retro

Questions
Do you consider yourself to be a trendy person? If so, in what ways?

Are you a fan of retro fashion? What are some examples of retro fashion?

Introduction
The word 'retro' implies a style that reminiscent of the past. Retro can be used to describe things that actually come from a past time period or things that are new, but designed in a way that is suggestive of a past style.
As an example, since rollerblades became popular in the 90s, few people bother with traditional roller skates anymore. So, if you saw someone skating down the street on roller skates, you could say, "Wow, roller skates, How retro"

Reminiscent - bringing to mind; stimulating memories


text:
package org.wso2.carbon.esb.nhttp.transport.json.test;

import junit.framework.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import java.io.File;

public class ESBJAVA4331MissingJSONEmptyArrayNHTTPTransport extends ESBIntegrationTest {

    private ServerConfigurationManager serverConfigurationManager;

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init();
        serverConfigurationManager =
                new ServerConfigurationManager(new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN));
        serverConfigurationManager.applyConfiguration(new File(getESBResourceLocation() + File.separator
                                                               + "nhttp" + File.separator + "transport" +
                                                               File.separator + "json" + File.separator + "synapse.properties"));
        super.init();
        verifyAPIExistence("testJsonEmptyArrayApi");

    }

    @Test(groups = "wso2.esb", description = "check whether Backend JSON payload is missing Json empty array elements " +
            "after flowing through NHTTP transport in response path back to client")
    public void testJSONEmptyArrayMissingNHTTPTransport() throws Exception {
        HttpResponse response = HttpRequestUtil.sendGetRequest(
                getApiInvocationURL("testJsonEmptyArray/testapi1"), null);
        Assert.assertTrue("Backend JSON payload is missing [] in Json empty array units after flowing through NHTTP transport"
                + "in response path back to client", response.getData()
                .contains("\"zeroElementArrayField\": []"));

        response = HttpRequestUtil.sendGetRequest(
                getApiInvocationURL("testJsonEmptyArray/testapi2"), null);
        Assert.assertTrue(
                "All number fields are not treated equally by Auto primitive function after flowing through NHTTP transport"
                        + "in response path back to client", response.getData().replaceAll("\\s", "").contains(
                        "[{\"numField1\":\"1\"},{\"numField2\":\"2\"},{\"numField3\":\"3\"},{\"numField4\":\"4\"}]"));

        response = HttpRequestUtil.sendGetRequest(
                getApiInvocationURL("testJsonEmptyArray/testapi3"), null);
        Assert.assertTrue("Backend JSON payload is missing [] in Json single element array units after flowing through NHTTP transport"
                + "in response path back to client", response.getData().replaceAll("\\s", "")
                .contains("\"singleElementArrayField\":[{\"numField1\":\"1\"}]"));

        response = HttpRequestUtil.sendGetRequest(
                getApiInvocationURL("testJsonEmptyArray/testapi4"), null);
        Assert.assertTrue("Backend JSON payload is missing [] in Json multiple element array units after flowing through NHTTP transport"
                + "in response path back to client", response.getData().replaceAll("\\s", "")
                .contains("\"multipleElementArrayField\":[{\"numField1\":\"1\"},{\"numField2\":\"2\"},"
                        + "{\"numField3\":\"3\"}]"));

    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        super.cleanup();
        serverConfigurationManager.restoreToLastConfiguration();
    }

}


text:
package org.apache.kafka.connect.runtime.rest.entities;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;
import java.util.Objects;

public class ConfigInfos {

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

    @JsonProperty("error_count")
    private final int errorCount;

    @JsonProperty("groups")
    private final List<String> groups;

    @JsonProperty("configs")
    private final List<ConfigInfo> configs;

    @JsonCreator
    public ConfigInfos(@JsonProperty("name") String name,
                       @JsonProperty("error_count") int errorCount,
                       @JsonProperty("groups") List<String> groups,
                       @JsonProperty("configs") List<ConfigInfo> configs) {
        this.name = name;
        this.groups = groups;
        this.errorCount = errorCount;
        this.configs = configs;
    }

    @JsonProperty
    public String name() {
        return name;
    }

    @JsonProperty
    public List<String> groups() {
        return groups;
    }

    @JsonProperty("error_count")
    public int errorCount() {
        return errorCount;
    }

    @JsonProperty("configs")
    public List<ConfigInfo> values() {
        return configs;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ConfigInfos that = (ConfigInfos) o;
        return Objects.equals(name, that.name) &&
               Objects.equals(errorCount, that.errorCount) &&
               Objects.equals(groups, that.groups) &&
               Objects.equals(configs, that.configs);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, errorCount, groups, configs);
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("[")
            .append(name)
            .append(",")
            .append(errorCount)
            .append(",")
            .append(groups)
            .append(",")
            .append(configs)
            .append("]");
        return sb.toString();
    }

}


text:
namespace slang.Compiler.Core.Parsing.Ast
{
    public class IntegerLiteral : Literal
    {
        public IntegerLiteral(string value) : base(value, "System.Int32")
        {
        }
    }
}


text:
Sample Widget
=============

How to setup:

1. Clone this repository in a prepared environment, now called devhost.tld, execute composer install.
2. To initialize the database, execute in shell: php bin/console doctrine:schema:generate
3. Open http://devhost.tld/user/create and create a user entry.
- OR -
3. Load included fixtures, with php bin/console doctrine:fixtures:load
4. Open http://devhost.tld/ . You shouldn't see anything special.
5. Edit app/Resources/views/default/index.html.twig and change the block "javascripts", use your chosen uuid as js filename.
- OR -
5. After migration, pick a uuid from /user and use it as a js filename in views/default/index.html.twig
6. Open http://devhost.tld/ again. You see a blue widget on the bottom right, with some rating from the chosen user.

The widget JS is empty if the uuid is invalid or does not exist. The site will still work, even if there is no script.
Of course, that would be different, if there'd be any frontend dependency on that widget...


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

namespace CSharp
{
    public class Evaluator
    {
        public static double Correct(
            IEnumerable<Observation> validationSet,
            BasicClassifier classifier)
        {
            return validationSet
                .Select(obs => Score(obs, classifier))
                .Average();
        }

        private static double Score(
            Observation obs,
            IClassifier classifier)
        {
            if (classifier.Predict(obs.Pixels) == obs.Label)
                return 1.0;
            else
                return 0.0;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Arcanedev\Notify;

use Arcanedev\Notify\Contracts\Notify as NotifyContract;
use Arcanedev\Notify\Contracts\Store as StoreContract;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\Macroable;

/**
 * Class     Notify
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class Notify implements NotifyContract
{
    /* -----------------------------------------------------------------
     |  Traits
     | -----------------------------------------------------------------
     */

    use Macroable;

    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /**
     * The session writer.
     *
     * @var \Arcanedev\Notify\Contracts\Store
     */
    private $store;

    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * Create a new flash notifier instance.
     *
     * @param  \Arcanedev\Notify\Contracts\Store  $store
     */
    public function __construct(StoreContract $store)
    {
        $this->setStore($store);
    }

    /* -----------------------------------------------------------------
     |  Getters & Setters
     | -----------------------------------------------------------------
     */

    /**
     * Get the store.
     *
     * @return \Arcanedev\Notify\Contracts\Store
     */
    public function store(): StoreContract
    {
        return $this->store;
    }

    /**
     * Set the store.
     *
     * @param  \Arcanedev\Notify\Contracts\Store  $store
     *
     * @return $this
     */
    public function setStore(StoreContract $store)
    {
        $this->store = $store;

        return $this;
    }

    /**
     * Get all the notifications.
     *
     * @return \Illuminate\Support\Collection
     */
    public function notifications(): Collection
    {
        return $this->store()->all();
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Flash an information message.
     *
     * @param  string  $message
     * @param  array   $extra
     *
     * @return $this
     */
    public function info(string $message, array $extra = [])
    {
        return $this->flash($message, 'info', $extra);
    }

    /**
     * Flash a success message.
     *
     * @param  string  $message
     * @param  array   $extra
     *
     * @return $this
     */
    public function success(string $message, array $extra = [])
    {
        return $this->flash($message, 'success', $extra);
    }

    /**
     * Flash an error message.
     *
     * @param  string  $message
     * @param  array   $extra
     *
     * @return $this
     */
    public function error(string $message, array $extra = [])
    {
        return $this->flash($message, 'danger', $extra);
    }

    /**
     * Flash a warning message.
     *
     * @param  string  $message
     * @param  array   $extra
     *
     * @return $this
     */
    public function warning(string $message, array $extra = [])
    {
        return $this->flash($message, 'warning', $extra);
    }

    /**
     * Flash a new notification.
     *
     * @param  string       $message
     * @param  string|null  $type
     * @param  array        $extra
     *
     * @return $this
     */
    public function flash($message, $type = 'info', array $extra = [])
    {
        $this->store()->push(compact('message', 'type', 'extra'));

        return $this;
    }

    /**
     * Forget the notification.
     */
    public function forget(): void
    {
        $this->store->forget();
    }

    /**
     * Check if it has notifications.
     *
     * @return bool
     */
    public function isEmpty(): bool
    {
        return $this->store()->isEmpty();
    }

    /**
     * Check if there is no notifications.
     *
     * @return bool
     */
    public function isNotEmpty(): bool
    {
        return $this->store()->isNotEmpty();
    }
}


text:
package main

import (
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"strings"
	_ "time/tzdata"

	"github.com/alecthomas/kong"
	"github.com/crazy-max/ftpgrab/v7/internal/app"
	"github.com/crazy-max/ftpgrab/v7/internal/config"
	"github.com/crazy-max/ftpgrab/v7/internal/logging"
	"github.com/crazy-max/ftpgrab/v7/pkg/utl"
	"github.com/rs/zerolog/log"
)

var (
	ftpgrab *app.FtpGrab
	cli     config.Cli
	version = "dev"
	meta    = config.Meta{
		ID:     "ftpgrab",
		Name:   "FTPGrab",
		Desc:   "Grab your files periodically from a remote FTP or SFTP server easily",
		URL:    "https://github.com/crazy-max/ftpgrab",
		Logo:   "https://raw.githubusercontent.com/crazy-max/ftpgrab/master/.res/ftpgrab.png",
		Author: "CrazyMax",
	}
)

func main() {
	var err error
	runtime.GOMAXPROCS(runtime.NumCPU())

	meta.Version = version
	meta.UserAgent = fmt.Sprintf("%s/%s go/%s %s", meta.ID, meta.Version, runtime.Version()[2:], strings.Title(runtime.GOOS))
	if meta.Hostname, err = os.Hostname(); err != nil {
		log.Fatal().Err(err).Msg("Cannot resolve hostname")
	}

	// Parse command line
	_ = kong.Parse(&cli,
		kong.Name(meta.ID),
		kong.Description(fmt.Sprintf("%s. More info: %s", meta.Desc, meta.URL)),
		kong.UsageOnError(),
		kong.Vars{
			"version": version,
		},
		kong.ConfigureHelp(kong.HelpOptions{
			Compact: true,
			Summary: true,
		}))

	// Init
	logging.Configure(cli)
	log.Info().Str("version", version).Msgf("Starting %s", meta.Name)

	// Handle os signals
	channel := make(chan os.Signal)
	signal.Notify(channel, os.Interrupt, utl.SIGTERM)
	go func() {
		sig := <-channel
		ftpgrab.Close()
		log.Warn().Msgf("Caught signal %v", sig)
		os.Exit(0)
	}()

	// Load configuration
	cfg, err := config.Load(cli, meta)
	if err != nil {
		log.Fatal().Err(err).Msg("Cannot load configuration")
	}
	log.Debug().Msg(cfg.String())

	// Init
	if ftpgrab, err = app.New(cfg); err != nil {
		log.Fatal().Err(err).Msgf("Cannot initialize %s", meta.Name)
	}

	// Start
	if err = ftpgrab.Start(); err != nil {
		log.Fatal().Err(err).Msgf("Cannot start %s", meta.Name)
	}
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.communote.server.widgets (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.communote.server.widgets

Interfaces

Widget

WidgetFactory

Classes

AbstractMultipleResultWidget

AbstractWidget

EmptyWidget

FormWidget

SimpleWidgetController

SimpleWidgetFactory

WidgetController

Exceptions

WidgetCreationException


text:
package com.lgc.wsh.inv;

import com.lgc.wsh.util.Almost;
import java.util.logging.*;

/** Implements a Vect by wrapping an array of doubles.
    The embedded data are exposed by a getData method.  For all practical
    purposes this member is public, except that this class must always
    point to the same array.  The implementation as an array
    is the point of this class, to avoid duplicate implementations
    elsewhere.  Multiple inheritance is prohibited and
    prevents the mixin pattern, but you can share the wrapped array
    as a private member of your own class,
    and easily delegate all implemented methods.
 */
public class ArrayVect1 implements Vect {
  /** wrapped data */
  private double[] _data = null;
  /** variance */
  private double _variance = 1.;
  @SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger("com.lgc.wsh.inv");
  private static final long serialVersionUID = 1L;

  /** Construct from an array of data.
      @param data This is the data that will be manipulated.
      @param variance The method multiplyInverseCovariance()
      will divide all samples by this number.  Pass a value
      of 1 if you do not care.
  */
  public ArrayVect1(double[] data, double variance) {
    init(data,variance);
  }

  /** To be used with init() */
  protected ArrayVect1() {}

  /** Construct from an array of data.
      @param data This is the data that will be manipulated.
      @param variance The method multiplyInverseCovariance()
      will divide all samples by this number.  Pass a value
      of 1 if you do not care.
  */
  protected void init(double[] data, double variance) {
    _data = data;
    _variance = variance;
  }

  /** Return the size of the embedded array
 * @return size of the embedded array */
  public int getSize() {return _data.length;}

  /** Get the embedded data
      @return Same array as passed to constructore.
   */
  public double[] getData() {
    return _data;
  }

  @Override
public ArrayVect1 clone() {
    try {
      ArrayVect1 result = (ArrayVect1) super.clone();
      result._data = result._data.clone();
      return result;
    } catch (CloneNotSupportedException ex) {
      IllegalStateException e = new IllegalStateException(ex.getMessage());
      e.initCause(ex);
      throw e;
    }
  }

  public double dot(VectConst other) {
    double result = 0;
    ArrayVect1 rhs = (ArrayVect1) other;
    for (int i=0; i<_data.length; ++i) {
      result += _data[i] * rhs._data[i];
    }
    return result;
  }

  @Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("(");
    for (int i=0; i<_data.length; ++i) {
      sb.append(""+_data[i]);
      if (i < _data.length -1) {sb.append(", ");}
    }
    sb.append(")");
    return sb.toString();
  }

  public void dispose() {
    _data = null;
  }

  public void multiplyInverseCovariance() {
    double scale = Almost.FLOAT.divide (1., getSize()*_variance, 0.);
    VectUtil.scale(this, scale);
  }

  public void constrain() {}

  public void postCondition() {}

  public void add(double scaleThis, double scaleOther, VectConst other)  {
    ArrayVect1 rhs = (ArrayVect1) other;
    for (int i=0; i<_data.length; ++i) {
      _data[i] = scaleThis*_data[i] + scaleOther*rhs._data[i];
    }
  }

  public void project(double scaleThis, double scaleOther, VectConst other)  {
    add(scaleThis, scaleOther, other);
  }

  public double magnitude() {
    return Almost.FLOAT.divide (this.dot(this), getSize()*_variance, 0.);
  }

  /** Run tests
     @param args command line
     @throws Exception
   */
  public static void main(String[] args) throws Exception {
    double[] a = new double[31];
    for (int i=0; i<a.length; ++i) {a[i] = i;}
    Vect v = new ArrayVect1(a, 3.);
    VectUtil.test(v);

    // test inverse covariance
    for (int i=0; i<a.length; ++i) {a[i] = 1;}
    v = new ArrayVect1(a, 3.);
    Vect w = v.clone();
    w.multiplyInverseCovariance();
    assert Almost.FLOAT.equal(1./3., v.dot(w));
    assert Almost.FLOAT.equal(1./3., v.magnitude());
  }

}