text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller {
	public function __construct() {
		parent::__construct();
		// Load database
		$this->load->model('login_database');
		// Load form helper library
        $this->load->helper('form');
        // Load form validation library
        $this->load->library('form_validation');
    }
public function index(){
        $data['user_data'] = $this->login_database->read('1');
	     if($data['user_data'] != false) {
		   $this->load->view('users',$data);
		  }
	     else {
		   $data = array(
		   'error_message' => 'No users found ...'
		  );
		  $this->load->view('users', $data);
		}
	}
public function registration(){
		$this->load->view('register');
	}
	// Validate and store registration data in database
public function add_user() {
 // Check validation for user input in SignUp form
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
	 if($this->form_validation->run() == FALSE) {
		  $this->load->view('register');
		}
	 else {
		$data = array(
		'username' => $this->input->post('username'),
		'email' => $this->input->post('email'),
		'password' => md5($this->input->post('password')),
        'created' => date('Y-m-d H:i:s'),
        'status' => '1',
        'level' => $this->input->post('type')
		);
		$result = $this->login_database->registration_insert($data);
	  if($result == 'registered') {
	    $this->session->set_flashdata('success_register','Registration Successful ...');
        redirect("users/");
		}
	 else {
		$data['error_message'] = $result;
        $data['add_username'] = $this->input->post('username');
        $data['add_email'] = $this->input->post('email');
		$this->load->view('register', $data);
		  }
		}
	}
public function delete_user($user) {
	 if(!isset($user)) {
		  redirect("users/");
		}
	 else {
		$result = $this->login_database->delete_user($user);
	  if($result == true) {
	    $this->session->set_flashdata('success_delete','Deletion Successful ...');
        redirect("users/");
		}
	  else {
		$this->session->set_flashdata('fail_delete','Unable to delete ...');
        redirect("welcome/users");
		  }
		}
	}

// Check for user login process
public function dashboard(){
     if(isset($this->session->userdata['logged_in'])){
          $this->load->view('dashboard');
        }
     else{
        $password = $this->input->post('password');
        $data = array(
		'username' => $this->input->post('username'),
		'password' => $password
		);
		$result = $this->login_database->login($data);
	 if($result != false) {
		$session_data = array(
		'username' => $result[0]->username,
        'password' => $password,
		'email' => $result[0]->email,
        'user_level' => $result[0]->level
		);
		// Add user data in session
		$this->session->set_userdata('logged_in', $session_data);
		$this->load->view('dashboard');
		}
	else {
		$data = array(
		'error_message' => 'Invalid Username or Password'
		);
		$this->load->view('login', $data);
		}
     }
   }
public function update(){
        $username = $this->input->post('username');
        $email = $this->input->post('email');
        $pass = $this->input->post('password');
        $password = md5($pass);
        $data = array(
		'password' => $password,
        'email' => $email
		);
    $result = $this->login_database->update($username,$data);
	 if($result != false) {
		$session_data = array(
		'username' => $username,
        'email' => $email,
        'password' => $pass,
        'user_level' => $this->session->userdata['logged_in']['user_level']
		);
		// Add user data in session
		$this->session->set_userdata('logged_in', $session_data);
 	    $data = array(
		'success_message' => 'Information updated ...'
		);
		$this->load->view('dashboard',$data);
		}
	else {
		$data = array(
		'error_message' => 'Update failed ...'
		);
		$this->load->view('dashboard', $data);
		}
   }
   }
?>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>All news • RNHANES</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

<link href="../pkgdown.css" rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>
      RNHANES

  Reference

    Articles

      Introduction to RNHANES

  News

Change log All releases

RNHANES 1.1

Switched to downloading NHANES files using https, instead of http.

Fixed a bug that prevented downloading data from any cycles after 2011-2012.

Contents

1.1

Developed by Herb Susmann.

Site built with pkgdown.

redpajama_set_name: RedPajamaGithub


text:
<title>Low-Pass Filter passlp</title>
<link rel="SHORTCUT ICON" href="favicon.ico">

<applet codebase="../afilter" code=AFilter.class archive=afilter.jar width=640 height=450>
Sorry, you need a Java-enabled browser to see the simulation.
<param name=pause value=20>
<param name=startCircuit value="passlp.txt">
<param name=startLabel   value="Low-Pass Filter passlp">
<param name=useFrame     value="false">
</applet>

This is a high-pass
      filter implemented using a resistor and a capacitor.  A
      high-pass filter passes
higher frequencies and attenuates lower
      frequencies.  The
      input frequency keeps changing, sweeping up and down the
      spectrum to demonstrate the change in response.
The capacitor passes higher frequencies, causing the output voltage to
      fluctuate more.  Lower frequencies are blocked, and there is
      reduced current across the resistor, keeping the
      output voltage closer to ground.

The breakpoint (-3 dB point) is
shown at the lower right, as "f.3db".

Next: Low-Pass Filter (RC)

Previous: High-Pass Filter (RC)

Index

java@falstad.com

Generated Sat Sep 19 2009


text:
class CommentsController < ApplicationController
  include JSONAPI::ActsAsResourceController
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def context
    { user: nil }
  end

  # https://github.com/cerebris/jsonapi-resources/pull/573
  def handle_exceptions(err)
    if JSONAPI.configuration.exception_class_whitelist.any? { |k| err.class.ancestors.include?(k) }
      raise err
    end

    super
  end

  def user_not_authorized
    head :forbidden
  end
end


text:
use super::autoderef;
use super::AutorefArgs;
use super::check_argument_types;
use super::check_expr;
use super::check_method_argument_types;
use super::err_args;
use super::FnCtxt;
use super::LvaluePreference;
use super::method;
use super::structurally_resolved_type;
use super::TupleArgumentsFlag;
use super::write_call;

use middle::infer;
use middle::ty::{self, Ty};
use syntax::ast;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::ptr::P;
use CrateCtxt;

/// Check that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
/// method that is called)
pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) {
    let tcx = ccx.tcx;
    let did = Some(trait_id);
    let li = &tcx.lang_items;

    if did == li.drop_trait() {
        span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
    } else if !tcx.sess.features.borrow().unboxed_closures {
        // the #[feature(unboxed_closures)] feature isn't
        // activated so we need to enforce the closure
        // restrictions.

        let method = if did == li.fn_trait() {
            "call"
        } else if did == li.fn_mut_trait() {
            "call_mut"
        } else if did == li.fn_once_trait() {
            "call_once"
        } else {
            return // not a closure method, everything is OK.
        };

        span_err!(tcx.sess, span, E0174,
                  "explicit use of unboxed closure method `{}` is experimental",
                  method);
        span_help!(tcx.sess, span,
                   "add `#![feature(unboxed_closures)]` to the crate attributes to enable");
    }
}

pub fn check_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                            call_expr: &ast::Expr,
                            callee_expr: &ast::Expr,
                            arg_exprs: &[P<ast::Expr>])
{
    check_expr(fcx, callee_expr);
    let original_callee_ty = fcx.expr_ty(callee_expr);
    let (callee_ty, _, result) =
        autoderef(fcx,
                  callee_expr.span,
                  original_callee_ty,
                  Some(callee_expr.id),
                  LvaluePreference::NoPreference,
                  |adj_ty, idx| {
                      let autoderefref = ty::AutoDerefRef { autoderefs: idx, autoref: None };
                      try_overloaded_call_step(fcx, call_expr, callee_expr,
                                               adj_ty, autoderefref)
                  });

    match result {
        None => {
            // this will report an error since original_callee_ty is not a fn
            confirm_builtin_call(fcx, call_expr, original_callee_ty, arg_exprs);
        }

        Some(CallStep::Builtin) => {
            confirm_builtin_call(fcx, call_expr, callee_ty, arg_exprs);
        }

        Some(CallStep::Overloaded(method_callee)) => {
            confirm_overloaded_call(fcx, call_expr, arg_exprs, method_callee);
        }
    }
}

enum CallStep<'tcx> {
    Builtin,
    Overloaded(ty::MethodCallee<'tcx>)
}

fn try_overloaded_call_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                      call_expr: &ast::Expr,
                                      callee_expr: &ast::Expr,
                                      adjusted_ty: Ty<'tcx>,
                                      autoderefref: ty::AutoDerefRef<'tcx>)
                                      -> Option<CallStep<'tcx>>
{
    // If the callee is a bare function or a closure, then we're all set.
    match structurally_resolved_type(fcx, callee_expr.span, adjusted_ty).sty {
        ty::ty_bare_fn(..) => {
            fcx.write_adjustment(callee_expr.id,
                                 callee_expr.span,
                                 ty::AdjustDerefRef(autoderefref));
            return Some(CallStep::Builtin);
        }

        _ => {}
    }

    // Try the options that are least restrictive on the caller first.
    for &(opt_trait_def_id, method_name) in [
        (fcx.tcx().lang_items.fn_trait(), token::intern("call")),
        (fcx.tcx().lang_items.fn_mut_trait(), token::intern("call_mut")),
        (fcx.tcx().lang_items.fn_once_trait(), token::intern("call_once")),
    ].iter() {
        let trait_def_id = match opt_trait_def_id {
            Some(def_id) => def_id,
            None => continue,
        };

        match method::lookup_in_trait_adjusted(fcx,
                                               call_expr.span,
                                               Some(&*callee_expr),
                                               method_name,
                                               trait_def_id,
                                               autoderefref.clone(),
                                               adjusted_ty,
                                               None) {
            None => continue,
            Some(method_callee) => {
                return Some(CallStep::Overloaded(method_callee));
            }
        }
    }

    None
}

fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                 call_expr: &ast::Expr,
                                 callee_ty: Ty<'tcx>,
                                 arg_exprs: &[P<ast::Expr>])
{
    let error_fn_sig;

    let fn_sig = match callee_ty.sty {
        ty::ty_bare_fn(_, &ty::BareFnTy {ref sig, ..}) => {
            sig
        }
        _ => {
            fcx.type_error_message(call_expr.span, |actual| {
                format!("expected function, found `{}`", actual)
            }, callee_ty, None);

            // This is the "default" function signature, used in case of error.
            // In that case, we check each argument against "error" in order to
            // set up all the node type bindings.
            error_fn_sig = ty::Binder(ty::FnSig {
                inputs: err_args(fcx.tcx(), arg_exprs.len()),
                output: ty::FnConverging(fcx.tcx().types.err),
                variadic: false
            });

            &error_fn_sig
        }
    };

    // Replace any late-bound regions that appear in the function
    // signature with region variables. We also have to
    // renormalize the associated types at this point, since they
    // previously appeared within a `Binder<>` and hence would not
    // have been normalized before.
    let fn_sig =
        fcx.infcx().replace_late_bound_regions_with_fresh_var(call_expr.span,
                                                              infer::FnCall,
                                                              fn_sig).0;
    let fn_sig =
        fcx.normalize_associated_types_in(call_expr.span, &fn_sig);

    // Call the generic checker.
    let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
    check_argument_types(fcx,
                         call_expr.span,
                         fn_sig.inputs.as_slice(),
                         arg_exprs.as_slice(),
                         AutorefArgs::No,
                         fn_sig.variadic,
                         TupleArgumentsFlag::DontTupleArguments);

    write_call(fcx, call_expr, fn_sig.output);
}

fn confirm_overloaded_call<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                    call_expr: &ast::Expr,
                                    arg_exprs: &[P<ast::Expr>],
                                    method_callee: ty::MethodCallee<'tcx>)
{
    let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
    let output_type = check_method_argument_types(fcx,
                                                  call_expr.span,
                                                  method_callee.ty,
                                                  call_expr,
                                                  arg_exprs.as_slice(),
                                                  AutorefArgs::No,
                                                  TupleArgumentsFlag::TupleArguments);
    let method_call = ty::MethodCall::expr(call_expr.id);
    fcx.inh.method_map.borrow_mut().insert(method_call, method_callee);
    write_call(fcx, call_expr, output_type);
}


text:
package com.google.javascript.jscomp.parsing;

import com.google.javascript.rhino.ErrorReporter;

/**
 * An error reporter which consumes all calls and performs no actions.
 *
 */
public abstract class NullErrorReporter  {
  private NullErrorReporter() {
  }

  public void error(String message, String sourceName, int line,
      int lineOffset) {
  }

  public void warning(String message, String sourceName, int line,
      int lineOffset) {
  }

  public static ErrorReporter forOldRhino() {
    return new OldRhinoNullReporter();
  }

  private static class OldRhinoNullReporter extends NullErrorReporter
      implements ErrorReporter {
  }
}


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { typedDependencies } from './dependenciesTyped.generated'
import { createSubtract } from '../../factoriesNumber.js'

export const subtractDependencies = {
  typedDependencies,
  createSubtract
}


text:
Not too long ago I was looking into [meteor hunting](http://www.livescience.com/33876-meteorite-hunting-guide.html).
Hunting for meteors is a pretty arduous process (boring) and I began to consider what kind of things might make it easier.
From there I conceived of the Meteor Tracker.  Using a few camera connected computers I imagine you could not
only detect meteors, but you may be able to determine their speed, origin, and possibly their landing location
(as long as they didn't burn up in the atmosphere).

### Why is this useful?
Firstly finding meteors can tell us a whole lot about our solar system.  It can tell us about its formation and early days.
Also detecting small meteors can often signify the arrival of larger meteoroids.  This is good for anticipating catastrophic
meteor events (make boom with earth).  Finally meteors are worth a lot of money and sentimental value (I want
a meteorite sword).

The basic premise is the take a few computers with cameras and to correlate meteor events as well as triangulate them.
There are a few steps I envision towards achieving this:

1.  We have to know where we are and where we are facing.  The only assumption I'm making at this point is
	that the camera is normal to the ground (that is to say pointing straight up).  I did some research and
	found [astrometry](http://astrometry.net/).  Astrometry takes an image of the stars and finds out where they are
	in the sky.  Using this data and knowledge of the current time, we can find out where we are and which direction
	we are facing.

2.  We have to capture meteor events.  The premise here is simple: check for changes in each image frame coming from the
	camera.  If we see something record it.  Now we may capture erroneous data such as airplanes and sattelites, but
	we can figure that out next.

3.  Correlate these events.  Match up several events from a few different units to determine which captured events
	are the same among them.  We can start by matching up timestamps that are withing a few seconds of each other.
	By knowing where the device is and which direction its facing we can narrow this down to determine which events
	are the same.

4.  Triangulate the trajectories.  We can use an overconstrained linear algebra matrix to incorporate as many
	cameras as we want.  (pure ray intersection doesn't really work here.  I'll go into detail in future posts)
	If we can capture several frames we can better estimate air resistance and extrapolate the entrance trajectory.

If we get all that, boom, we have a system capable of telling us a ton of information about falling stars.

Optional bonus things:
- a local webserver for changing settings and viewing the most up to date images
- a remote webserver for compiling all tracker data points and making them available to the public
- a cool 3D viewer of impact events and earth intersection trajectories

### Whats the current status?
Currently it can only capture meteor events and there is a rough web server for viewing current images.  The biggest problem
at this point is getting good enough hardware (especially cameras) to capture good meteor events.

UPDATE WITH PART 2 SOON

\-/EOL/


text:
<TITLE>Review for Amantes (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Amantes (1991)

reviewed by
Brian L. Johnson

                                  AMANTES
                         (American title: LOVERS)
                       A film review by Ken Johnson
                        Copyright 1993 Ken Johnson

105 min., R, Drama, 1991, In Spanish with English subtitles
Director: Vincente Aranda
Cast: Victoria Abril, Jorge Sanz, Maribel Verdu, Enrique Cerro,
      Mabel Escano, Alicia Agut

     Ex-soldier Jorge Sanz moves into the town where his girlfriend
Maribel Verdu lives.  As soon as he gets a job and money, they will get
married.  Sanz rents a room from Victoria Abril.  She seduces him, and
Sanz finds that he is falling out of love with Verdu, and into love with
Abril.

     AMANTES is a rather sad film and is based on a true story.   I
don't recommend this film for everybody, although if it comes to a
theater near you for a cheap enough rate, you might be interested in
going to see it.  If the film sounds interesting to you from the review
I have written, I suggest that you do attempt to see this film at a
theater as I don't know if it will ever be released on video cassette.
On a scale of zero to five, I give AMANTES a four.  AMANTES is rated R
for strong sexual content, explicit language, adult situations, brief
female nudity, and brief male nudity.

     The actors/actresses in this film do a very good job.   Victoria
Abril is excellent as Jorge Sanz's landlady.  She is seductive, yet you
can see the evil behind what she does.  Jorge Sanz is great as the poor
man who is deeply in love with Maribel Verdu.  As he gets to know
Victoria Abril he starts to fall in love with her; or is it just the
sexual things that she does with him?  Maribel Verdu is excellent as
Jorge Sanz's girlfriend who sees herself losing him.  She has to convert
to Victoria Abril's tactics if she wants to keep Jorge Sanz for herself.

     This film reminded me a lot of the Pamela Smart case that happened
in New Hampshire last year.  It is almost the exact story, except
instead of a husband, the third person is a girlfriend.  The film is
quite well written.  The end of the film is rushed and a little
confusing.  There are a few slow spots, and I vaguely remember one place
that moved along too quickly, but other than that I don't remember any
problems with the writing.  The film presented the material rather well,
not making it too depressing, especially considering the content.
However, at some points, especially towards the end, the film does get
depressing.

--------
Ken Johnson
blj@mithrandir.cs.unh.edu

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
describe :net_httpheader_each_name, :shared => true do
  before :each do
    @headers = NetHTTPHeaderSpecs::Example.new
    @headers["My-Header"] = "test"
    @headers.add_field("My-Other-Header", "a")
    @headers.add_field("My-Other-Header", "b")
  end

  describe "when passed a block" do
    it "yields each header key to the passed block (keys in lower case)" do
      res = []
      @headers.send(@method) do |key|
        res << key
      end
      res.sort.should == ["my-header", "my-other-header"]
    end
  end

  describe "when passed no block" do
    it "returns an Enumerator" do
      enumerator = @headers.send(@method)
      enumerator.should be_an_instance_of(enumerator_class)

      res = []
      enumerator.each do |key|
        res << key
      end
      res.sort.should == ["my-header", "my-other-header"]
    end
  end
end


text:
<?php

namespace Byron\DOM;

class DOMXPath extends \DOMXPath
{

    public function __construct(\Byron\DOM\DOMDocument $doc)
    {
        parent::__construct($doc->getDocument());
    }

}


text:
package org.eclipse.jnosql.diana.reader;

import jakarta.nosql.ValueReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.*;

class ByteValueReaderTest {

    private ValueReader valueReader;

    @BeforeEach
    public void init() {
        valueReader = new ByteReader();
    }

    @Test
    public void shouldValidateCompatibility() {
        assertTrue(valueReader.isCompatible(Byte.class));
        assertFalse(valueReader.isCompatible(AtomicBoolean.class));
        assertFalse(valueReader.isCompatible(Boolean.class));
    }

    @Test
    public void shouldConvert() {
        Integer number = 10;
        assertEquals(Byte.valueOf((byte) 10), valueReader.read(Integer.class, number));
        assertEquals(Byte.valueOf((byte) 10), valueReader.read(Integer.class, 10.00));
        assertEquals(Byte.valueOf((byte) 10), valueReader.read(Integer.class, "10"));
    }

}


text:
require 'aws/ses'

module Backup
  module Notifier
    class Ses < Base

      ##
      # Amazon Simple Email Service (SES) Credentials
      attr_accessor :access_key_id, :secret_access_key

      ##
      # SES Region
      attr_accessor :region

      ##
      # Sender Email Address
      attr_accessor :from

      ##
      # Receiver Email Address
      attr_accessor :to

      ##
      # CC receiver Email Address
      attr_accessor :cc

      ##
      # BCC receiver Email Address
      attr_accessor :bcc

      ##
      # Set reply to email address
      attr_accessor :reply_to

      def initialize(model, &block)
        super
        instance_eval(&block) if block_given?

        @region ||= 'eu-west-1'
        @send_log_on ||= [:warning, :failure]
      end

      ##
      # Array of statuses for which the log file should be attached.
      #
      # Available statuses are: `:success`, `:warning` and `:failure`.
      # Default: [:warning, :failure]
      attr_accessor :send_log_on

      private

      def client
        AWS::SES::Base.new(
          :access_key_id => access_key_id,
          :secret_access_key => secret_access_key,
          :server => "email.#{region}.amazonaws.com"
        )
      end

      ##
      # Notify the user of the backup operation results.
      #
      # `status` indicates one of the following:
      #
      # `:success`
      # : The backup completed successfully.
      # : Notification will be sent if `on_success` is `true`.
      #
      # `:warning`
      # : The backup completed successfully, but warnings were logged.
      # : Notification will be sent, including a copy of the current
      # : backup log, if `on_warning` or `on_success` is `true`.
      #
      # `:failure`
      # : The backup operation failed.
      # : Notification will be sent, including a copy of the current
      # : backup log, if `on_failure` is `true`.
      #
      def notify!(status)
        email = ::Mail.new
        email.to       = to
        email.from     = from
        email.cc       = cc
        email.bcc      = bcc
        email.reply_to = reply_to
        email.subject  = message.call(model, :status => status_data_for(status))

        send_log = send_log_on.include?(status)
        template = Backup::Template.new({ :model => model, :send_log => send_log })
        email.body = template.result('notifier/mail/%s.erb' % status.to_s)

        if send_log
          email.convert_to_multipart
          email.attachments["#{ model.time }.#{ model.trigger }.log"] = {
            :mime_type => 'text/plain;',
            :content   => Logger.messages.map(&:formatted_lines).flatten.join("\n")
          }
        end

        client.send_raw_email(email)
      end
    end
  end
end


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

/**
 * @fileoverview Directive for the Video rich-text component.
 *
 * IMPORTANT NOTE: The naming convention for customization args that are passed
 * into the directive is: the name of the parameter, followed by 'With',
 * followed by the name of the arg.
 */

require('domain/utilities/UrlInterpolationService.ts');
require('services/AutoplayedVideosService.ts');
require('services/ContextService.ts');
require('services/HtmlEscaperService.ts');

angular.module('oppia').directive('oppiaNoninteractiveVideo', [
  '$sce', 'HtmlEscaperService', 'UrlInterpolationService',
  function($sce, HtmlEscaperService, UrlInterpolationService) {
    return {
      restrict: 'E',
      scope: {},
      bindToController: {},
      templateUrl: UrlInterpolationService.getExtensionResourceUrl(
        '/rich_text_components/Video/directives/video_directive.html'),
      controllerAs: '$ctrl',
      controller: [
        '$attrs', 'ContextService', '$element',
        'AutoplayedVideosService', 'PAGE_CONTEXT', '$timeout', '$window',
        function($attrs, ContextService, $element,
            AutoplayedVideosService, PAGE_CONTEXT, $timeout, $window) {
          var ctrl = this;
          var start = (
            HtmlEscaperService.escapedJsonToObj($attrs.startWithValue));
          var end = HtmlEscaperService.escapedJsonToObj($attrs.endWithValue);

          ctrl.videoId = HtmlEscaperService.escapedJsonToObj(
            $attrs.videoIdWithValue);
          ctrl.timingParams = '&start=' + start + '&end=' + end;
          ctrl.autoplaySuffix = '&autoplay=0';

          $timeout(function() {
            // Check whether creator wants to autoplay this video or not
            var autoplayVal = HtmlEscaperService.escapedJsonToObj(
              $attrs.autoplayWithValue);

            // This code helps in visibility of video. It checks whether
            // mid point of video frame is in the view or not.
            var rect = angular.element($element)[0].getBoundingClientRect();
            var clientHeight = $window.innerHeight;
            var clientWidth = $window.innerWidth;
            var isVisible = ((rect.left + rect.right) / 2 < clientWidth &&
              (rect.top + rect.bottom) / 2 < clientHeight) &&
              (rect.left > 0 && rect.right > 0);

            // Autoplay if user is in learner view and creator has specified
            // to autoplay given video.
            if (ContextService.getPageContext() ===
              PAGE_CONTEXT.EXPLORATION_PLAYER && autoplayVal) {
              // If it has been autoplayed then do not autoplay again.
              if (
                !AutoplayedVideosService.hasVideoBeenAutoplayed(
                  ctrl.videoId) && isVisible) {
                ctrl.autoplaySuffix = '&autoplay=1';
                AutoplayedVideosService.addAutoplayedVideo(ctrl.videoId);
              }
            }

            ctrl.videoUrl = $sce.trustAsResourceUrl(
              'https://www.youtube.com/embed/' + ctrl.videoId + '?rel=0' +
              ctrl.timingParams + ctrl.autoplaySuffix);
          }, 900);
          // (^)Here timeout is set to 900ms. This is time it takes to bring the
          // frame to correct point in browser and bring user to the main
          // content. Smaller delay causes checks to be performed even before
          // the player displays the content of the new card.

          // This following check disables the video in Editor being caught
          // by tabbing while in Exploration Editor mode.
          if (ContextService.isInExplorationEditorMode()) {
            ctrl.tabIndexVal = -1;
          }
        }]
    };
  }
]);


text:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Translation } from 'app/shared/models';

@Pipe({
  name: 'mytranslate'
})
export class MyTranslatePipe implements PipeTransform {
  transform(value: Translation[], args0?: string): string {
    const country = navigator.language.substring(0, 2).toUpperCase();
    const translate = value.find(p => p.country === country);
    return translate != null ? translate.value : args0;
  }
}


text:
import {
  RECEIVE_SAMPLE_DETAIL, RECEIVE_CHANGES, CHANGE_SELECTED_SAMPLE,
} from '../actions/actions.js';
import {Seq, Map as ImmutableMap} from 'immutable';

export const sampleIds = (state=Seq(), action) => {
  switch (action.type) {
  case RECEIVE_SAMPLE_DETAIL:
    return Seq([action.sampleId]);
  case RECEIVE_CHANGES:
    return action.samples.keySeq();
  default:
    return state;
  }
};

export const samplesById = (state=ImmutableMap(), action) => {
  switch (action.type) {
  case RECEIVE_CHANGES:
  case RECEIVE_SAMPLE_DETAIL:
    return action.samples;
  default:
    return state;
  }
};

export const sampleDetailId = (state=null, action) => {
  switch (action.type) {
  case CHANGE_SELECTED_SAMPLE:
    return action.sampleId;
  default:
    return state;
  }
};

export const sampleDetailUUID = (state=null, action) => {
  switch (action.type) {
  case RECEIVE_SAMPLE_DETAIL:
    return action.sampleId;
  default:
    return state;
  }
};


text:
body > ul > li small {
  color: gray;
  font-weight: normal;
}

#login input {
  padding-left: 75px;
}

#reviewrequest .summary {
  border-bottom: 1px solid #999999;
  padding: 12px 10px;
  text-align: left;
}

#reviewrequest h3 {
  font-size: 14px;
  margin: 0;
  padding: 0 0 5px 0;
}

#reviewrequest > fieldset {
  font-size: 12px;
}

#reviewrequest .row {
  border: 0;
  line-height: 20px;
  min-height: 20px;
  padding: 2px 0;
}

#reviewrequest .descriptionRow {
  border-top: 1px solid #999999;
}

#reviewrequest .row > label {
  line-height: inherit;
  text-align: right;
  vertical-align: top;
  width: 65px;
  color: #666666;
}

#reviewrequest .row > div {
  text-align: left;
  padding: 0 10px 0 85px;
}

#reviewrequest .controls .whiteButton {
  float: left;
  font-size: 12px;
  margin-bottom: 20px;
  width: 100px;
}

#reviewrequest .controls .whiteButton:first-child {
  margin-right: 10px;
}

#reviewrequest > h2 {
  clear: both;
}

.review .body {
  padding: 12px 10px;
  text-align: left;
}

.review .reply-comments {
  margin: 20px 0 0 0;
  padding: 0;
}

.review .reply-comments .reply-comment {
  display: inline;
}

.review .reply-comments .reply-comment dd {
  margin-left: 10px;
}

.review .reply-comments .reply-comment dl {
  border-left: 2px #D0D0D0 solid;
  margin: 0px;
  padding: 5px;
}

.review .reply-comments .reply-comment dt a {
  color: #AB5603;
  font-size: 1.1em;
  font-weight: bold;
  text-decoration: none;
}

.review .reply-comments .reply-comment dt .timestamp {
  display: block;
}

.review .reply-comments .reply-comment.draft dt a {
  color: #4e9a06;
}

.review .reply-comments .reply-comment dt span {
  color: #487858;
  font-weight: normal;
}

.review .controls {
  display: none;
}

table.sidebyside {
  background: white;
  border: 1px #C0C0C0 solid;
  border-collapse: collapse;
  margin: 2px;
  padding: 2px;
}

table.sidebyside col.left {
  border-right: 1px #C0C0C0 solid;
  width: 50%;
}

table.sidebyside col.line {
  border-right: 1px #C0C0C0 solid;
}

table.sidebyside col.right {
  width: 50%;
}

table.sidebyside .filename {
  font-size: 12px;
  font-weight: bold;
  margin: 4px 0;
  padding: 0;
}

table.sidebyside td {
  min-width: 20px;
}

table.sidebyside pre {
  font-size: 10px;
  line-height: default;
  margin: 0;
  padding: 0;
  white-space: default;
}

table.sidebyside thead th {
  background: #F0F0F0;
  border-bottom: 1px #C0C0C0 solid;
  font-size: 12px;
  font-weight: bold;
  padding: 4px 8px;
  text-align: left;
  text-overflow: ellipsis;
}

table.sidebyside tbody th {
  background: #F0F0F0;
  font-size: 10px;
  text-align: right;
  vertical-align: top;
}

table.sidebyside tr.first td,
table.sidebyside tr.first th {
  border-top: 1px #D0D0D0 solid;
}

table.sidebyside tr.last td,
table.sidebyside tr.last th {
  border-bottom: 1px #D0D0D0 solid;
}

table.sidebyside tbody.binary td {
  background: #dbebff;
  padding: 4px;
}

table.sidebyside tbody.collapsed a {
  text-decoration: underline;
  color: black;
}

table.sidebyside tbody.collapsed td {
  background: #e4d9cb;
  font-size: x-small;
  text-align: center;
}

table.sidebyside tbody.collapsed th {
  background: #e4d9cb;
}

table.sidebyside tbody.delete {
  background: #ffc5ce;
}

table.sidebyside tbody.delete th {
  background: #ffc5ce;
}

table.sidebyside tbody.delete tr.selected * {
  background: #dfb1b1;
}

table.sidebyside tbody.insert {
  background: #c5ffc4;
}

table.sidebyside tbody.insert th {
  background: #c5ffc4;
}

table.sidebyside tbody.insert tr.selected * {
  background: #9ae298;
}

table.sidebyside tbody.replace {
  background: #fdfebc;
}

table.sidebyside tbody.replace th {
  background: #fdfebc;
}

table.sidebyside tbody.replace tr.selected * {
  background: #e2e179;
}

table.sidebyside tbody.replace .hl {
  background: #eff23d;
}

.shipit {
  display: inline;
  color: #006000;
}

.dialog > fieldset > label {
  font-size: 12px;
}

.dialog > fieldset > .error {
  color: #770000;
  margin-top: 8px;
  text-align: left;
}


text:
"""
maaluokitus

todo doc
"""
import sys, os, getopt
import http.client as httplib
import json
from time import localtime, strftime

import dboperator

def show(message):
  print(strftime("%Y-%m-%d %H:%M:%S", localtime())+" "+message)

def makerow():
  return {
    'koodi':None, 'nimi':None, 'nimi_sv':None, 'nimi_en':None, 'alkupvm':None, 'loppupvm':None,
    'maanosatkoodi':None, 'maanosatnimi':None, 'maanosatnimi_sv':None, 'maanosatnimi_en':None,
    'maanosat2koodi':None, 'maanosat2nimi':None, 'maanosat2nimi_sv':None, 'maanosat2nimi_en':None,
    'maanosat3koodi':None, 'maanosat3nimi':None, 'maanosat3nimi_sv':None, 'maanosat3nimi_en':None
  }

# get value from json
def jv(jsondata, key):
  if key in jsondata:
    return jsondata[key]
  return None

def getnimi(i,kieli):
  for m in i["metadata"]:
    if m["kieli"] == kieli:
      return m["nimi"]
  return None

def load(secure,hostname,url,schema,table,codeset,verbose=False):
  if verbose: show("begin")

  row = makerow()
  dboperator.columns(row)

  if verbose: show("empty %s.%s"%(schema,table))
  dboperator.empty(schema,table)

  url = url % codeset # replace placeholder
  if secure:
    httpconn = httplib.HTTPSConnection(hostname)
    show("load securely from "+hostname+url)
  else:
    httpconn = httplib.HTTPConnection(hostname)
    show("load from "+hostname+url)

  reqheaders = {'Caller-Id': '1.2.246.562.10.2013112012294919827487.vipunen'}
  httpconn.request('GET', url, headers=reqheaders)
  #httpconn.request('GET', url)
  r = httpconn.getresponse()
  j = json.loads(r.read())
  cnt = 0
  for i in j:
    cnt += 1
    row = makerow()

    row["koodi"] = jv(i,"koodiArvo")
    row["nimi"] = getnimi(i,"FI")
    row["nimi_sv"] = getnimi(i,"SV")
    row["nimi_en"] = getnimi(i,"EN")
    row["alkupvm"] = jv(i,"voimassaAlkuPvm")
    row["loppupvm"] = jv(i,"voimassaLoppuPvm")

    httpconn.request('GET', "/koodisto-service/rest/json/relaatio/sisaltyy-ylakoodit/%s" % i["koodiUri"], headers=reqheaders)
    rr = httpconn.getresponse()
    jj = json.loads(rr.read())
    for ii in jj:
      classification = "maanosat"
      level = ""
      if len(ii["koodiArvo"])==3:
        level = "3"
      elif len(ii["koodiArvo"])==2:
        level = "2"
      # else default
      if ii["koodisto"]["koodistoUri"] == classification:
        row[classification+level+"koodi"] = jv(ii,"koodiArvo")
        row[classification+level+"nimi"] = getnimi(ii,"FI")
        row[classification+level+"nimi_sv"] = getnimi(ii,"SV")
        row[classification+level+"nimi_en"] = getnimi(ii,"EN")

    if verbose: show("%d -- %s"%(cnt,row["koodi"]))
    dboperator.insert(hostname+url,schema,table,row)

  dboperator.close()

  if verbose: show("ready")

def usage():
  print("""
usage: maaluokitus.py [-s|--secure] [-H|--hostname <hostname>] [-u|--url <url>] [-e|--schema <schema>] [-t|--table <table>] [-c|--codeset <codeset>] [-v|--verbose]

secure defaults to being secure (HTTPS) (so no point in using this argument at all)
hostname defaults to $OPINTOPOLKU then to "virkailija.opintopolku.fi"
url defaults to "/koodisto-service/rest/json/%s/koodi" (do notice the %s in middle which is a placeholder for codeset argument)
schema defaults to $SCHEMA then to "" (for database default if set)
table defaults to $TABLE then to "sa_maaluokitus"
codeset defaults to "maatjavaltiot2" (probably not going to change -- ever)
""")

def main(argv):
  # variables from arguments with possible defaults
  secure = True # default secure, so always secure!
  hostname = os.getenv("OPINTOPOLKU") or "virkailija.opintopolku.fi"
  url = "/koodisto-service/rest/json/%s/koodi" # nb %s
  schema = os.getenv("SCHEMA") or ""
  table = os.getenv("TABLE") or "sa_maaluokitus"
  codeset = "maatjavaltiot2"
  verbose = False

  try:
    opts, args = getopt.getopt(argv,"sH:u:e:t:c:v",["secure","hostname=","url=","schema=","table=","codeset=","verbose"])
  except getopt.GetoptError as err:
    print(err)
    usage()
    sys.exit(2)
  for opt, arg in opts:
    if opt in ("-s", "--secure"): secure = True
    elif opt in ("-H", "--hostname"): hostname = arg
    elif opt in ("-u", "--url"): url = arg
    elif opt in ("-e", "--schema"): schema = arg
    elif opt in ("-t", "--table"): table = arg
    elif opt in ("-c", "--codeset"): codeset = arg
    elif opt in ("-v", "--verbose"): verbose = True
  if not hostname or not url or not schema or not table or not codeset:
    usage()
    sys.exit(2)

  load(secure,hostname,url,schema,table,codeset,verbose)

if __name__ == "__main__":
  main(sys.argv[1:])


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="en" flag="gb" title="English">
    <string_add name="_bx_payment_lmi_cpt_providers"><![CDATA[Providers]]></string_add>
    <string_add name="_bx_payment_grid_column_title_pdrs_caption"><![CDATA[Caption]]></string_add>
    <string_add name="_bx_payment_grid_column_title_pdrs_description"><![CDATA[Description]]></string_add>
    <string_add name="_bx_payment_grid_column_title_pdrs_for_visitor"><![CDATA[For visitors]]></string_add>
    <string_add name="_bx_payment_grid_column_title_pdrs_for_single"><![CDATA[One Time]]></string_add>
    <string_add name="_bx_payment_grid_column_title_pdrs_for_recurring"><![CDATA[Recurring]]></string_add>
</resources>


text:
function save_config(cfg)

outdir = fullfile('.ftb', 'config');
if ~exist(outdir, 'dir')
    mkdir(outdir);
end

save(fullfile(outdir, [cfg.stage.full '.mat']), 'cfg');

end


text:
def alphabeticShift(input_string):
    # Shift alphabetic characters in a string by one.
    # Define a function to shift a character.
    def shift(char):
        # Normalize the position of the character between 0 and 26.
        pos = ord(char) - ord('a')
        # Shift it by one.
        pos = (pos + 1) % 26
        # Convert it back to a character.
        return chr(pos + ord('a'))
    # Use the function in a `map` call to apply it to every character.
    return "".join(map(shift, input_string))


text:
package org.apache.flink.runtime.fs.hdfs;

import org.apache.flink.testutils.ClassLoaderUtils;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.TestLogger;

import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/** Tests that validate the behavior of the Hadoop File System Factory. */
public class HadoopFreeFsFactoryTest extends TestLogger {

    /**
     * This test validates that the factory can be instantiated and configured even when Hadoop
     * classes are missing from the classpath.
     */
    @Test
    public void testHadoopFactoryInstantiationWithoutHadoop() throws Exception {
        // we do reflection magic here to instantiate the test in another class
        // loader, to make sure no hadoop classes are in the classpath

        final String testClassName = "org.apache.flink.runtime.fs.hdfs.HadoopFreeTests";

        final URL[] urls = ClassLoaderUtils.getClasspathURLs();

        ClassLoader parent = getClass().getClassLoader();
        ClassLoader hadoopFreeClassLoader = new HadoopFreeClassLoader(urls, parent);
        Class<?> testClass = Class.forName(testClassName, false, hadoopFreeClassLoader);
        Method m = testClass.getDeclaredMethod("test");

        try {
            m.invoke(null);
        } catch (InvocationTargetException e) {
            ExceptionUtils.rethrowException(e.getTargetException(), "exception in method");
        }
    }

    // ------------------------------------------------------------------------

    private static final class HadoopFreeClassLoader extends URLClassLoader {

        private final ClassLoader properParent;

        HadoopFreeClassLoader(URL[] urls, ClassLoader parent) {
            super(urls, null);
            properParent = parent;
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (name.startsWith("org.apache.hadoop")) {
                throw new ClassNotFoundException(name);
            } else if (name.startsWith("org.apache.log4j")) {
                return properParent.loadClass(name);
            } else {
                return super.loadClass(name);
            }
        }
    }
}


text:
<?php $this->load->view('components/_header') ?>
<?php $this->load->view('components/_nav') ?>

Account Settings

                    Regenerate API Key
                    <a href="<?php echo site_url('account') ?>" class="right">

                <form method="post" action="<?php echo site_url('account/edit/token') ?>">
                    <input type="hidden" name="spk" value="<?php echo $this->config->item('stripe_publishable_key') ?>" />

WARNING This may have unintended consequences and cannot be undone.

Are you absolutely sure you want to regenerate your API key?

                                    <a href="<?php echo site_url('account') ?>">Cancel

                                    <input type="submit" value="Regenerate API Key" class="gi-button" />

                </form>

<?php $this->load->view('components/_footer') ?>


text:
package pgstore

// Copyright (c) 2014 André Luiz Alves Moraes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import (
	"database/sql"
	"fmt"
	"github.com/andrebq/exp/pandora"
	_ "github.com/lib/pq"
	"io"
	"io/ioutil"
	"sync"
	"time"
)

type querier interface {
	QueryRow(query string, args ...interface{}) *sql.Row
	Query(query string, args ...interface{}) (*sql.Rows, error)
	Exec(query string, args ...interface{}) (sql.Result, error)
}

var (
	blobStoreDef = []string{
		`do
		$$
		begin
			create sequence pgstore_seq_blobs increment 1 minvalue 1 maxvalue 9223372036854775807 start 1 cache 1;
		exception when duplicate_table then
		end
		$$ language plpgsql;`,
		`create table if not exists pgstore_blobs(id integer not null default nextval('pgstore_seq_blobs'), blobid bytea, data bytea)`,
		`create table if not exists pgstore_blobs_ref(id integer not null, blobid bytea, delta integer not null)`,
	}

	messageStoreDef = []string{
		`do
		$$
		begin
			create sequence pgstore_seq_messages increment 1 minvalue 1 maxvalue 9223372036854775807 start 1 cache 1;
		exception when duplicate_table then
		end
		$$ language plpgsql;`,
		`create table if not exists pgstore_messages(
			id integer not null default nextval('pgstore_seq_messages'),
			mid bytea not null,
			lid bytea,
			leaseuntil timestamp,
			status int not null,
			receivedat timestamp not null,
			sendwhen timestamp not null,
			deliverycount int not null,
			senderid int not null,
			receiverid int not null
		)`,
		`do
		$$
		begin
			alter table pgstore_messages
				add constraint pgstore_unq_messages_mid unique(mid);
		exception when duplicate_table then
		end
		$$ language plpgsql;`,
		`create table if not exists pgstore_messageboxes (id integer not null default nextval('pgstore_seq_messages'), name text not null)`,
	}

	ErrKeyNotFound = pandora.ApiError("key not found")
)

type memoryBuffer interface {
	Bytes() []byte
}

// MessageStore implements pandora.MessageStore using postgresql as backend
type MessageStore struct {
	sync.RWMutex
	conn *sql.DB
	bs   *BlobStore
}

// OpenMessageStore opens the message store with the given parameters
func OpenMessageStore(user, pwd, host, dbname string) (*MessageStore, error) {
	sqldb, err := sql.Open("postgres", fmt.Sprintf("user=%v dbname=%v password=%v host=%v sslmode=disable", user, dbname, pwd, host))
	if err != nil {
		return nil, err
	}
	return &MessageStore{
		conn: sqldb,
	}, err
}

func (ms *MessageStore) DeleteMessages() error {
	_, err := ms.conn.Exec("delete from pgstore_messages")
	return err
}

func (ms *MessageStore) InitTables() (err error) {
	for _, cmd := range messageStoreDef {
		_, thisErr := ms.conn.Exec(cmd)
		if err == nil && thisErr != nil {
			err = thisErr
		}
	}
	return
}

func (ms *MessageStore) Reenqueue(now time.Time) error {
	return reEnqueueMessages(ms.conn, time.Now())
}

// take all messages that have a lease time expired and
// remove the lock information.
//
// Confirmed messages aren't touched
func reEnqueueMessages(db querier, now time.Time) error {
	_, err := db.Exec(`update pgstore_messages
		set lid = null, leaseuntil = null
		where lid is not null and leaseuntil < $1 and status <> $2`,
		now, pandora.StatusConfirmed)
	return err
}

func fetchHeaders(out []pandora.Message, db querier, inbox string, now, min time.Time) ([]pandora.Message, error) {
	err := reEnqueueMessages(db, now)
	if err != nil {
		return nil, err
	}

	inboxId, err := findInbox(db, inbox, false)
	if err != nil {
		return nil, err
	}
	results, err := db.Query(`select mid, status, receivedat, sendwhen, deliverycount
		from pgstore_messages
		where receiverid = $1
			and lid is null
			and sendwhen <= $2
			and receivedat > $3
			and status <> $4
		order by receivedat asc, sendwhen asc
		limit $5`, inboxId, now, min, pandora.StatusConfirmed, len(out))
	if err != nil {
		return nil, err
	}
	defer results.Close()
	var idx int
	var buf []byte
	for results.Next() {
		var msg *pandora.Message
		if idx < len(out) {
			msg = &out[idx]
		} else {
			break
		}
		msg.Mid = &pandora.SHA1Key{}
		err := results.Scan(&buf, &msg.Status, &msg.ReceivedAt, &msg.SendWhen, &msg.DeliveryCount)
		if err != nil {
			return out[:idx], err
		}
		copy(msg.Mid.Bytes(), buf)
		idx++
	}
	return out[:idx], err
}

func fetchLatestMessage(msg *pandora.Message, db querier, inbox string, now time.Time, dur time.Duration) error {
	err := reEnqueueMessages(db, now)
	if err != nil {
		return err
	}
	inboxId, err := findInbox(db, inbox, false)
	if err != nil {
		return err
	}
	var buf []byte
	var id int64
	err = db.QueryRow(`select id, mid, status, receivedat, sendwhen, deliverycount
		from pgstore_messages
		where receiverid = $1
			and lid is null
			and sendwhen <= $2
			and status <> $3
		order by sendwhen asc
		limit 1`, inboxId, now, pandora.StatusConfirmed).Scan(&id, &buf, &msg.Status, &msg.ReceivedAt, &msg.SendWhen, &msg.DeliveryCount)
	if err == sql.ErrNoRows {
		return pandora.ErrNoMessages
	}
	if err != nil {
		return err
	}
	msg.Mid = &pandora.SHA1Key{}
	copy(msg.Mid.Bytes(), buf)
	msg.CalcualteLeaseFor(now, dur)

	_, err = db.Exec("update pgstore_messages set lid = $1, deliverycount = deliverycount + 1, leaseuntil = $2 where id = $3", msg.Lid.Bytes(), msg.LeasedUntil, id)
	return err
}

func findInbox(db querier, inbox string, create bool) (id int64, err error) {
	if len(inbox) == 0 {
		err = pandora.ErrInvalidMailBox
		return
	}
	err = db.QueryRow("select id from pgstore_messageboxes where name = $1", inbox).Scan(&id)
	if err == sql.ErrNoRows {
		if create {
			// create the inbox
			err = db.QueryRow("insert into pgstore_messageboxes(name) values ($1) returning id", inbox).Scan(&id)
		} else {
			err = pandora.ErrSenderNotFound
		}
	}
	return
}

func findSenderReceiver(db querier, msg *pandora.Message, create bool) (sid int64, rid int64, err error) {
	senderName, receiverName := msg.Sender(), msg.Receiver()
	sid, err = findInbox(db, senderName, create)
	if err != nil {
		return
	}

	rid, err = findInbox(db, receiverName, create)
	if err != nil {
		return
	}
	return
}

// Enqueue will place the message inside the receiver inbox
func (ms *MessageStore) Enqueue(msg *pandora.Message) error {
	msg.Status = pandora.StatusNotDelivered
	msg.CalculateMid()
	return doInsideTransaction(ms.conn, func(tx querier) error {
		senderId, receiverId, err := findSenderReceiver(tx, msg, true)
		if err != nil {
			return err
		}
		var id int64
		err = tx.QueryRow("insert into pgstore_messages(mid, status, receivedat, sendwhen, deliverycount, senderid, receiverid) values ($1, $2, $3, $4, $5, $6, $7) returning id",
			msg.Mid.Bytes(), msg.Status, msg.ReceivedAt, msg.SendWhen, msg.DeliveryCount, senderId, receiverId).Scan(&id)
		return err
	})
}

// FetchAndLockLatest will read and lock the latest message for the given receiver
func (ms *MessageStore) FetchAndLockLatest(recv string, dur time.Duration) (*pandora.Message, error) {
	var msg pandora.Message
	err := doInsideTransaction(ms.conn, func(tx querier) error {
		return fetchLatestMessage(&msg, tx, recv, time.Now(), dur)
	})
	return &msg, err
}

func (ms *MessageStore) FetchHeaders(out []pandora.Message, recv string, receivedAt time.Time) (int, error) {
	var actual []pandora.Message
	err := doInsideTransaction(ms.conn, func(tx querier) error {
		var err error
		actual, err = fetchHeaders(out, ms.conn, recv, time.Now(), receivedAt)
		return err
	})
	return len(actual), err
}

func (ms *MessageStore) Ack(mid, lid pandora.Key, status pandora.AckStatus) error {
	return doInsideTransaction(ms.conn, func(tx querier) error {
		var id int64
		switch status {
		case pandora.StatusConfirmed, pandora.StatusRejected:
		default:
			return pandora.ErrUnableToChangeStatus
		}

		err := tx.QueryRow(`update pgstore_messages
			set status = $1, lid = null, leaseuntil = null
			where mid = $2 and lid = $3 and leaseuntil >= $4
			returning id`, status, mid.Bytes(), lid.Bytes(), time.Now()).Scan(&id)
		if err != nil {
			return err
		}
		if id == 0 {
			return pandora.ErrUnableToChangeStatus
		}
		return nil
	})
}

// BlobStore implements pandora.BlobStore using postgresql as backend
type BlobStore struct {
	sync.RWMutex
	conn *sql.DB
}

// InitTables create all the required tables to use the blob store
func (bs *BlobStore) InitTables() (err error) {
	for _, cmd := range blobStoreDef {
		_, thisErr := bs.conn.Exec(cmd)
		if err == nil && thisErr != nil {
			err = thisErr
		}
	}
	return
}

// Close the store
func (bs *BlobStore) Close() error {
	return bs.conn.Close()
}

// GetData read the contents stored under the k key
func (bs *BlobStore) GetData(out []byte, k pandora.Key) ([]byte, error) {
	var id int64
	var size int
	var err error
	exists, err := bs.keyExistsInDb(&id, k)
	if !exists {
		return nil, ErrKeyNotFound
	}
	err = bs.conn.QueryRow(`select bs.id, octet_length(bs.data) from pgstore_blobs bs where bs.blobid = $1`, k.Bytes()).Scan(&id, &size)
	if err != nil {
		return nil, err
	}
	out = sliceOfSize(out, size)
	err = bs.conn.QueryRow(`select bs.data from pgstore_blobs bs where bs.id = $1`, id).Scan(&out)
	return out, err
}

func (bs *BlobStore) UpdateRefCount(k pandora.Key, delta int) error {
	var err error
	var id int64
	exists, err := bs.keyExistsInDb(&id, k)
	if !exists {
		return ErrKeyNotFound
	}
	_, err = bs.conn.Exec(`insert into pgstore_blobs_ref(id, blobid, delta) values ($1, $2, $3)`, id, k.Bytes(), delta)
	return err
}

// PutData write the contents of data and return the key used to store the data
func (bs *BlobStore) PutData(k pandora.Key, data []byte) (pandora.Key, error) {
	kw := pandora.SHA1KeyWriter{}
	kw.Write(data)
	actual := kw.Key()

	if k != nil && len(k.Bytes()) >= len(actual.Bytes()) {
		// avoid allocating outside the stack
		copy(k.Bytes(), actual.Bytes())
	} else {
		// use the heap
		k = actual
	}
	err := bs.insert(k, data)
	return k, err
}

func (bs *BlobStore) keyExistsInDb(id *int64, key pandora.Key) (bool, error) {
	err := bs.conn.QueryRow("select id from pgstore_blobs_ref where blobid = $1", key.Bytes()).Scan(id)
	if err == sql.ErrNoRows {
		return false, nil
	} else {
		if err != nil {
			return false, err
		}
	}
	return *id > 0, nil
}

func doInsideTransaction(db *sql.DB, fn func(tx querier) error) (err error) {
	var tx *sql.Tx
	tx, err = db.Begin()
	if err != nil {
		return err
	}
	defer func() {
		// if we had a panic
		// ensure that we rollback
		// and resend the panic
		if p := recover(); p != nil {
			tx.Rollback()
			panic(p)
		}
		// save the error from the function
		if err == nil {
			err = tx.Commit()
		} else {
			tx.Rollback()
		}
	}()
	err = fn(tx)
	return
}

// if data have a Bytes() []byte method, then it is used instead of a copy
func (bs *BlobStore) insert(out pandora.Key, data []byte) error {
	var id int64
	var err error
	exists, err := bs.keyExistsInDb(&id, out)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}
	return doInsideTransaction(bs.conn, func(tx querier) error {
		err := tx.QueryRow(`insert into pgstore_blobs(blobid, data) values ($1, $2) returning id`, out.Bytes(), data).Scan(&id)
		if err != nil {
			return err
		}
		_, err = tx.Exec(`insert into pgstore_blobs_ref(id, blobid, delta) values ($1, $2, $3)`, id, out.Bytes(), 0)
		if err != nil {
			return err
		}
		return err
	})
}

func readFull(data io.Reader) ([]byte, error) {
	switch data := data.(type) {
	case memoryBuffer:
		return data.Bytes(), nil
	default:
		return ioutil.ReadAll(data)
	}
	panic("not reached")
	return nil, nil
}

func sliceOfSize(old []byte, sz int) []byte {
	if cap(old) >= sz {
		return old[0:sz]
	}
	return make([]byte, sz)
}

// OpenBlobStore returns the blobstore using the provided user, password, host and dbname
func OpenBlobStore(user, pwd, host, dbname string) (*BlobStore, error) {
	sqldb, err := sql.Open("postgres", fmt.Sprintf("user=%v dbname=%v password=%v host=%v sslmode=disable", user, dbname, pwd, host))
	if err != nil {
		return nil, err
	}
	return &BlobStore{
		conn: sqldb,
	}, err
}


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

    angular
        .module('GVA.Voting', ['ngRoute', 'ngDialog', 'ngStorage', 'GVA.Common', 'GVA.Poll'])
        .config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
                when('/Vote/:pollId/:tokenId?', {
                    templateUrl: function (params) {
                        return '../Routes/Vote/' + params['pollId'];
                    }
                })
                .when('/Results/:pollId/:tokenId?', {
                    templateUrl: function (params) {
                        return '../Routes/Results/' + params['pollId'];
                    }
                });
        }]);
})();


text:
void random_testu01_smallcrush(int argc, char **argv)
{
    random_testu01(::bbattery_RepeatSmallCrush, argc, argv);
}


text:
package com.edu.fireeyes.adapter;

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

import com.edu.fireeyes.R;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class AddBookCheckListViewAdapter extends BaseExpandableListAdapter{

	private Context context;
	private List<String> Title = null,selItemIds=null;
	private ArrayList<ArrayList<ChildItem>> Content = null;

	public static class ChildItem{
		public ChildItem(){}
		public ChildItem(String cId,String cName){
			this.sub_id=cId;
			this.sub_name=cName;
		}
		public String sub_id;
		public String sub_name;
	}
	public AddBookCheckListViewAdapter(Context context) {
		this.context = context;
	}

	public void setDatas(List<String> Title,ArrayList<ArrayList<ChildItem>> Content,List<String> selItemIds){
		this.Title = Title;
		this.Content = Content;
		this.selItemIds=selItemIds;
	}

	@Override
	public int getGroupCount() {
		return Title.size();
	}
	@Override
	public int getChildrenCount(int groupPosition) {
		return Content.get(groupPosition).size();
	}
	@Override
	public Object getGroup(int groupPosition) {
		return null;
	}
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return null;
	}
	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}
	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}
	@Override
	public boolean hasStableIds() {
		return false;
	}
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.item_add_book_check_listview, null);
			holder = new ViewHolder();
			holder.tvTitle = (TextView)convertView.findViewById(R.id.item_add_book_check_listview_tv_title);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tvTitle.setText(Title.get(groupPosition));

		return convertView;
	}
	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.item_add_book_listview_item_list, null);
			holder = new ViewHolder();
			holder.cBox = (CheckBox)convertView.findViewById(R.id.item_add_book_check_listview_item_cbox);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		ChildItem cItem=Content.get(groupPosition).get(childPosition);
		holder.cBox.setText(cItem.sub_name);
		if(selItemIds.contains(cItem.sub_id))holder.cBox.setChecked(true);
		else holder.cBox.setChecked(false);
		return convertView;
	}

	class ViewHolder{
		TextView tvTitle;
		CheckBox cBox;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}
}


text:
package org.webbitserver.easyremote.inbound;

import com.google.gson.Gson;

public class GsonInboundDispatcher extends InboundDispatcher {

    private final Gson gson = new Gson();

    public GsonInboundDispatcher(Object server, Class<?> clientType) {
        super(server, clientType);
    }

    @Override
    protected InboundMessage unmarshalInboundRequest(String msg) {
        return gson.fromJson(msg, ActionArgsTuple.class);
    }

    // Populated by GSON.
    private static class ActionArgsTuple implements InboundMessage {
        String action;
        Object[] args;

        @Override
        public String method() {
            return action;
        }

        @Override
        public Object[] args() {
            return args;
        }
    }

}


text:
'use strict';

import everyLimit from './everyLimit';
import doLimit from './internal/doLimit';

/**
 * The same as `every` but runs only a single async operation at a time.
 *
 * @name everySeries
 * @static
 * @memberOf async
 * @see async.every
 * @alias allSeries
 * @category Collection
 * @param {Array|Object} coll - A collection to iterate over.
 * @param {Function} iteratee - A truth test to apply to each item in the
 * collection in parallel. The iteratee is passed a `callback(err, truthValue)`
 * which must be called with a  boolean argument once it has completed. Invoked
 * with (item, callback).
 * @param {Function} [callback] - A callback which is called after all the
 * `iteratee` functions have finished. Result will be either `true` or `false`
 * depending on the values of the async tests. Invoked with (err, result).
 */
export default doLimit(everyLimit, 1);


text:
package org.fife.rsta.ac.less;

import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.List;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.text.JTextComponent;

import org.fife.rsta.ac.css.PropertyValueCompletionProvider;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.FunctionCompletion;

/**
 * The main completion provider for Less code.
 *
 * @author Robert Futrell
 * @version 1.0
 */
class LessCodeCompletionProvider extends PropertyValueCompletionProvider {

	private List<Completion> functionCompletions;

	/**
	 * Constructor.
	 */
	LessCodeCompletionProvider() {
		super(true);
		try {
			this.functionCompletions = createFunctionCompletions();
		} catch (IOException ioe) { // Never happens
			throw new RuntimeException(ioe);
		}
	}

	/**
	 * Overridden to handle Less properly.
	 */
	@Override
	protected boolean addLessCompletions(List<Completion> completions,
			LexerState state, JTextComponent comp, String alreadyEntered) {

		boolean modified = false;

		if (alreadyEntered != null && alreadyEntered.length() > 0 &&
				alreadyEntered.charAt(0) == '@') {
			addLessVariableCompletions(completions, comp, alreadyEntered);
			modified = true;
		}

		if (state == LexerState.VALUE) {
			addLessBuiltinFunctionCompletions(completions, alreadyEntered);
			modified = true;
		}

		return modified;

	}

	private void addLessBuiltinFunctionCompletions(List<Completion> completions,
			String alreadyEntered) {
		completions.addAll(functionCompletions);
	}

	private void addLessVariableCompletions(List<Completion> completions,
			JTextComponent comp, String alreadyEntered) {
		// TODO: Implement me
	}

	private List<Completion> createFunctionCompletions() throws IOException {

		Icon functionIcon = loadIcon("methpub_obj");

		List<Completion> completions;
		completions = loadFromXML("data/less_functions.xml");
		for (Completion fc : completions) {
			((FunctionCompletion)fc).setIcon(functionIcon);
		}

		Collections.sort(completions);
		return completions;
	}

	/**
	 * Loads an icon by file name.
	 * Note that, if Less completion support gets more icons, we should
	 * create an IconFactory class and remove this method.
	 *
	 * @param name The icon file name.
	 * @return The icon.
	 */
	private Icon loadIcon(String name) {
		String imageFile = "img/" + name + ".gif";
		URL res = getClass().getResource(imageFile);
		if (res==null) {
			// IllegalArgumentException is what would be thrown if res
			// was null anyway, we're just giving the actual arg name to
			// make the message more descriptive
			throw new IllegalArgumentException("icon not found: " + imageFile);
		}
		return new ImageIcon(res);
	}

}


text:
package assertions

import "testing"

func TestShouldStartWith(t *testing.T) {
	serializer = newFakeSerializer()

	fail(t, so("", ShouldStartWith), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("", ShouldStartWith, "asdf", "asdf"), "This assertion requires exactly 1 comparison values (you provided 2).")

	pass(t, so("", ShouldStartWith, ""))
	fail(t, so("", ShouldStartWith, "x"), "x||Expected '' to start with 'x' (but it didn't)!")
	pass(t, so("abc", ShouldStartWith, "abc"))
	fail(t, so("abc", ShouldStartWith, "abcd"), "abcd|abc|Expected 'abc' to start with 'abcd' (but it didn't)!")

	pass(t, so("superman", ShouldStartWith, "super"))
	fail(t, so("superman", ShouldStartWith, "bat"), "bat|sup...|Expected 'superman' to start with 'bat' (but it didn't)!")
	fail(t, so("superman", ShouldStartWith, "man"), "man|sup...|Expected 'superman' to start with 'man' (but it didn't)!")

	fail(t, so(1, ShouldStartWith, 2), "Both arguments to this assertion must be strings (you provided int and int).")
}

func TestShouldNotStartWith(t *testing.T) {
	fail(t, so("", ShouldNotStartWith), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("", ShouldNotStartWith, "asdf", "asdf"), "This assertion requires exactly 1 comparison values (you provided 2).")

	fail(t, so("", ShouldNotStartWith, ""), "Expected '<empty>' NOT to start with '<empty>' (but it did)!")
	fail(t, so("superman", ShouldNotStartWith, "super"), "Expected 'superman' NOT to start with 'super' (but it did)!")
	pass(t, so("superman", ShouldNotStartWith, "bat"))
	pass(t, so("superman", ShouldNotStartWith, "man"))

	fail(t, so(1, ShouldNotStartWith, 2), "Both arguments to this assertion must be strings (you provided int and int).")
}

func TestShouldEndWith(t *testing.T) {
	serializer = newFakeSerializer()

	fail(t, so("", ShouldEndWith), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("", ShouldEndWith, "", ""), "This assertion requires exactly 1 comparison values (you provided 2).")

	pass(t, so("", ShouldEndWith, ""))
	fail(t, so("", ShouldEndWith, "z"), "z||Expected '' to end with 'z' (but it didn't)!")
	pass(t, so("xyz", ShouldEndWith, "xyz"))
	fail(t, so("xyz", ShouldEndWith, "wxyz"), "wxyz|xyz|Expected 'xyz' to end with 'wxyz' (but it didn't)!")

	pass(t, so("superman", ShouldEndWith, "man"))
	fail(t, so("superman", ShouldEndWith, "super"), "super|...erman|Expected 'superman' to end with 'super' (but it didn't)!")
	fail(t, so("superman", ShouldEndWith, "blah"), "blah|...rman|Expected 'superman' to end with 'blah' (but it didn't)!")

	fail(t, so(1, ShouldEndWith, 2), "Both arguments to this assertion must be strings (you provided int and int).")
}

func TestShouldNotEndWith(t *testing.T) {
	fail(t, so("", ShouldNotEndWith), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("", ShouldNotEndWith, "", ""), "This assertion requires exactly 1 comparison values (you provided 2).")

	fail(t, so("", ShouldNotEndWith, ""), "Expected '<empty>' NOT to end with '<empty>' (but it did)!")
	fail(t, so("superman", ShouldNotEndWith, "man"), "Expected 'superman' NOT to end with 'man' (but it did)!")
	pass(t, so("superman", ShouldNotEndWith, "super"))

	fail(t, so(1, ShouldNotEndWith, 2), "Both arguments to this assertion must be strings (you provided int and int).")
}

func TestShouldContainSubstring(t *testing.T) {
	serializer = newFakeSerializer()

	fail(t, so("asdf", ShouldContainSubstring), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("asdf", ShouldContainSubstring, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")

	fail(t, so(123, ShouldContainSubstring, 23), "Both arguments to this assertion must be strings (you provided int and int).")

	pass(t, so("asdf", ShouldContainSubstring, "sd"))
	fail(t, so("qwer", ShouldContainSubstring, "sd"), "sd|qwer|Expected 'qwer' to contain substring 'sd' (but it didn't)!")
}

func TestShouldNotContainSubstring(t *testing.T) {
	fail(t, so("asdf", ShouldNotContainSubstring), "This assertion requires exactly 1 comparison values (you provided 0).")
	fail(t, so("asdf", ShouldNotContainSubstring, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")

	fail(t, so(123, ShouldNotContainSubstring, 23), "Both arguments to this assertion must be strings (you provided int and int).")

	pass(t, so("qwer", ShouldNotContainSubstring, "sd"))
	fail(t, so("asdf", ShouldNotContainSubstring, "sd"), "Expected 'asdf' NOT to contain substring 'sd' (but it did)!")
}

func TestShouldBeBlank(t *testing.T) {
	serializer = newFakeSerializer()

	fail(t, so("", ShouldBeBlank, "adsf"), "This assertion requires exactly 0 comparison values (you provided 1).")
	fail(t, so(1, ShouldBeBlank), "The argument to this assertion must be a string (you provided int).")

	fail(t, so("asdf", ShouldBeBlank), "|asdf|Expected 'asdf' to be blank (but it wasn't)!")
	pass(t, so("", ShouldBeBlank))
}

func TestShouldNotBeBlank(t *testing.T) {
	fail(t, so("", ShouldNotBeBlank, "adsf"), "This assertion requires exactly 0 comparison values (you provided 1).")
	fail(t, so(1, ShouldNotBeBlank), "The argument to this assertion must be a string (you provided int).")

	fail(t, so("", ShouldNotBeBlank), "Expected value to NOT be blank (but it was)!")
	pass(t, so("asdf", ShouldNotBeBlank))
}


text:
package com.siyeh.igfixes.classlayout.class_may_be_interface;

class X {
  void test() {
    interface <caret>Foo {}

    class Bar implements Foo {}
  }
}


text:
define([
	"src/oskari/oskari",
	"./service",
	"src/mapping/service/MapLayerService"
], function(Oskari) {
	Oskari.bundleCls('service-base');
	Oskari.bundleCls('service-map');
});


text:
1. If you don't have it, [download TagUI here](https://tagui.readthedocs.io/en/latest/setup.html) (free open-source RPA tool by AI Singapore)
2. Download and unzip [Word Add-in zip file](https://github.com/kelaberetiv/TagUI/releases/download/v6.64.0/TagUIWordAddInSetupV3.15.zip) (double-click Setup.exe to start installing)
3. For any questions, please let us know on [our Telegram group](https://t.me/rpa_chat) or [weekly Zoom Q&A](https://github.com/kelaberetiv/TagUI/issues/914)

PS - Check out this [11-min video by RPA Learners](https://www.youtube.com/watch?v=mtiuzU6e4XE) on installing and running your first bot

![Word Add-in](https://raw.githubusercontent.com/kelaberetiv/TagUI/master/src/office/word/word_addin_v3.png)

---

# Microsoft Excel Add-in v3

1. If you don't have it, [download TagUI here](https://tagui.readthedocs.io/en/latest/setup.html) (free open-source RPA tool by AI Singapore)
2. Download and unzip [Excel Add-in zip file](https://github.com/kelaberetiv/TagUI/releases/download/v6.64.0/TagUIExcelAddInSetupv3.06.zip) (double-click Setup.exe to start installing)
3. For any questions, please let us know on [our Telegram group](https://t.me/rpa_chat) or [weekly Zoom Q&A](https://github.com/kelaberetiv/TagUI/issues/914)

![Excel Add-in](https://raw.githubusercontent.com/kelaberetiv/TagUI/master/src/office/excel/excel_addin_v3.png)


text:
{-# LANGUAGE BangPatterns          #-}
{-# LANGUAGE CPP                   #-}
{-# LANGUAGE MagicHash             #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies          #-}

module Math.NumberTheory.ArithmeticFunctions.Moebius
  ( Moebius(..)
  , runMoebius
  , sieveBlockMoebius
  ) where

import Control.Monad (forM_)
import Control.Monad.ST (runST)
import Data.Bits
import Data.Int
import Data.Word
#if __GLASGOW_HASKELL__ < 803
import Data.Semigroup
#endif
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Primitive as P
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as MU
import GHC.Exts
import GHC.Integer.GMP.Internals
import Unsafe.Coerce

import Math.NumberTheory.Roots (integerSquareRoot)
import Math.NumberTheory.Primes
import Math.NumberTheory.Utils.FromIntegral

import Math.NumberTheory.Logarithms

-- | Represents three possible values of <https://en.wikipedia.org/wiki/Möbius_function Möbius function>.
data Moebius
  = MoebiusN -- ^ -1
  | MoebiusZ -- ^  0
  | MoebiusP -- ^  1
  deriving (Eq, Ord, Show)

-- | Convert to any numeric type.
runMoebius :: Num a => Moebius -> a
runMoebius m = fromInteger (S# (dataToTag# m -# 1#))

fromMoebius :: Moebius -> Int8
fromMoebius m = intToInt8 $ I# (dataToTag# m)
{-# INLINE fromMoebius #-}

toMoebius :: Int8 -> Moebius
toMoebius i = let !(I# i#) = int8ToInt i in tagToEnum# i#
{-# INLINE toMoebius #-}

newtype instance U.MVector s Moebius = MV_Moebius (P.MVector s Int8)
newtype instance U.Vector    Moebius = V_Moebius  (P.Vector    Int8)

instance U.Unbox Moebius

instance M.MVector U.MVector Moebius where
  {-# INLINE basicLength #-}
  {-# INLINE basicUnsafeSlice #-}
  {-# INLINE basicOverlaps #-}
  {-# INLINE basicUnsafeNew #-}
  {-# INLINE basicInitialize #-}
  {-# INLINE basicUnsafeReplicate #-}
  {-# INLINE basicUnsafeRead #-}
  {-# INLINE basicUnsafeWrite #-}
  {-# INLINE basicClear #-}
  {-# INLINE basicSet #-}
  {-# INLINE basicUnsafeCopy #-}
  {-# INLINE basicUnsafeGrow #-}
  basicLength (MV_Moebius v) = M.basicLength v
  basicUnsafeSlice i n (MV_Moebius v) = MV_Moebius $ M.basicUnsafeSlice i n v
  basicOverlaps (MV_Moebius v1) (MV_Moebius v2) = M.basicOverlaps v1 v2
  basicUnsafeNew n = MV_Moebius <$> M.basicUnsafeNew n
  basicInitialize (MV_Moebius v) = M.basicInitialize v
  basicUnsafeReplicate n x = MV_Moebius <$> M.basicUnsafeReplicate n (fromMoebius x)
  basicUnsafeRead (MV_Moebius v) i = toMoebius <$> M.basicUnsafeRead v i
  basicUnsafeWrite (MV_Moebius v) i x = M.basicUnsafeWrite v i (fromMoebius x)
  basicClear (MV_Moebius v) = M.basicClear v
  basicSet (MV_Moebius v) x = M.basicSet v (fromMoebius x)
  basicUnsafeCopy (MV_Moebius v1) (MV_Moebius v2) = M.basicUnsafeCopy v1 v2
  basicUnsafeMove (MV_Moebius v1) (MV_Moebius v2) = M.basicUnsafeMove v1 v2
  basicUnsafeGrow (MV_Moebius v) n = MV_Moebius <$> M.basicUnsafeGrow v n

instance G.Vector U.Vector Moebius where
  {-# INLINE basicUnsafeFreeze #-}
  {-# INLINE basicUnsafeThaw #-}
  {-# INLINE basicLength #-}
  {-# INLINE basicUnsafeSlice #-}
  {-# INLINE basicUnsafeIndexM #-}
  {-# INLINE elemseq #-}
  basicUnsafeFreeze (MV_Moebius v) = V_Moebius <$> G.basicUnsafeFreeze v
  basicUnsafeThaw (V_Moebius v) = MV_Moebius <$> G.basicUnsafeThaw v
  basicLength (V_Moebius v) = G.basicLength v
  basicUnsafeSlice i n (V_Moebius v) = V_Moebius $ G.basicUnsafeSlice i n v
  basicUnsafeIndexM (V_Moebius v) i = toMoebius <$> G.basicUnsafeIndexM v i
  basicUnsafeCopy (MV_Moebius mv) (V_Moebius v) = G.basicUnsafeCopy mv v
  elemseq _ = seq

instance Semigroup Moebius where
  MoebiusZ <> _ = MoebiusZ
  _ <> MoebiusZ = MoebiusZ
  MoebiusP <> a = a
  a <> MoebiusP = a
  _ <> _ = MoebiusP

instance Monoid Moebius where
  mempty  = MoebiusP
  mappend = (<>)

-- | Evaluate the Möbius function over a block.
-- Value of @f@ at 0, if zero falls into block, is undefined.
--
-- Based on the sieving algorithm from p. 3 of <https://arxiv.org/pdf/1610.08551.pdf Computations of the Mertens function and improved bounds on the Mertens conjecture> by G. Hurst. It is approximately 5x faster than 'Math.NumberTheory.ArithmeticFunctions.SieveBlock.sieveBlockUnboxed'.
--
-- >>> sieveBlockMoebius 1 10
-- [MoebiusP,MoebiusN,MoebiusN,MoebiusZ,MoebiusN,MoebiusP,MoebiusN,MoebiusZ,MoebiusZ,MoebiusP]
sieveBlockMoebius
  :: Word
  -> Word
  -> U.Vector Moebius
sieveBlockMoebius _ 0 = U.empty
sieveBlockMoebius lowIndex' len'
  = (unsafeCoerce :: U.Vector Word8 -> U.Vector Moebius) $ runST $ do
    as <- MU.replicate len (0x80 :: Word8)
    forM_ ps $ \p -> do
      let offset  = negate lowIndex `mod` p
          offset2 = negate lowIndex `mod` (p * p)
          l :: Word8
          l = intToWord8 $ intLog2 p .|. 1
      forM_ [offset, offset + p .. len - 1] $
        MU.unsafeModify as (+ l)
      forM_ [offset2, offset2 + p * p .. len - 1] $ \ix ->
        MU.unsafeWrite as ix 0
    forM_ [0 .. len - 1] $ \ix ->
      MU.unsafeModify as (mapper ix) ix
    U.unsafeFreeze as

  where
    lowIndex :: Int
    lowIndex = wordToInt lowIndex'

    len :: Int
    len = wordToInt len'

    highIndex :: Int
    highIndex = lowIndex + len - 1

    -- Bit fiddling in 'mapper' is correct only
    -- if all sufficiently small (<= 191) primes has been sieved out.
    ps :: [Int]
    ps = map unPrime [nextPrime 2 .. precPrime (191 `max` integerSquareRoot highIndex)]

    mapper :: Int -> Word8 -> Word8
    mapper ix val
      | val .&. 0x80 == 0x00
      = 1
      | word8ToInt (val .&. 0x7F) < intLog2 (ix + lowIndex) - 5
        - (if ix + lowIndex >= 0x100000   then 2 else 0)
        - (if ix + lowIndex >= 0x10000000 then 1 else 0)
      = (val .&. 1) `shiftL` 1
      | otherwise
      = ((val .&. 1) `xor` 1) `shiftL` 1


text:
using System.IO;
using System.Threading;

namespace Scada
{
    /// <summary>
    /// File creation listener
    /// <para>Прослушиватель создания файла</para>
    /// <remarks>
    /// The class is used for receiving stop service command when running on Mono .NET framework
    /// <para>Класс используется для получения команды остановки службы при выполнении в Mono .NET framework</para>
    /// </remarks>
    /// </summary>
    public class FileListener
    {
        private string fileName; // имя ожидаемого файла
        private Thread thread;   // поток ожидания файла

        /// <summary>
        /// Обнаружен ожидаемый файл
        /// </summary>
        public volatile bool FileFound;

        /// <summary>
        /// Конструктор, ограничивающий создание объекта без параметров
        /// </summary>
        protected FileListener()
        {

        }

        /// <summary>
        /// Конструктор
        /// </summary>
        public FileListener(string fileName)
        {
            FileFound = false;
            this.fileName = fileName;
            thread = new Thread(new ThreadStart(WaitForFile));
            thread.Priority = ThreadPriority.BelowNormal;
            thread.Start();
        }

        /// <summary>
        /// Ожидать появления файла
        /// </summary>
        private void WaitForFile()
        {
            while (!FileFound)
            {
                if (File.Exists(fileName))
                    FileFound = true;
                else
                    Thread.Sleep(ScadaUtils.ThreadDelay);
            }
        }

        /// <summary>
        /// Удалить файл
        /// </summary>
        public void DeleteFile()
        {
            try
            {
                File.Delete(fileName);
            }
            catch { }
        }

        /// <summary>
        /// Прервать ожидание файла
        /// </summary>
        public void Abort()
        {
            if (thread != null)
            {
                thread.Abort();
                thread = null;
            }
        }
    }
}


text:
<?php
namespace Pmp\Sdk\Exception;

/**
 * API 401 errors
 */
class AuthException extends RemoteException {

}


text:
/*
* The HTML strategy is more involved than the API ones
* because
*/
var utils = require('utilities')
  , model = require('model')
  , strategy = function (content, options) {

      // Where to redirect to on a success event
      var params = this.params
        , type
          // Check the content for an errors hash
        , isFailure = (content.errors && typeof content.errors === 'object')
        , response
        , controllerName = this.name ?
            utils.string.getInflection(this.name, 'filename', 'plural') : null
        , redirect

          // Default routes to redirect to
        , successRedirects = {
            create: {id: content.id}
          , update: {id: content.id}
          , remove: {}
          }
        , failureRedirects = {
            create: {controller: controllerName, action: 'add'}
          , update: {controller: controllerName, action:'edit', id: content.id}
          , remove: {controller: controllerName, action:'edit', id: content.id}
          }

          /**
          * Select the appropriate redirect URL for the current situation
          * @return {Boolean|Object} - false if no redirect
          *   should occur, a route object if otherwise
          */
        , getRedirect = function () {
            var location = options.location
                // Select the appropriate defaults for the situation
              , redirects = isFailure ? failureRedirects : successRedirects;

            // Don't redirect if the user explicitly set location to false
            if(location === false) {
              return false;
            }
            else {
              // If the user defined a location, use that
              if(location) {
                return location;
              }
              else {
                // Otherwise look it up in the defaults
                return redirects[params.action] || false;
              }
            }
          }

          /**
          * Sets the appropriate flash message for the current situation
          */
        , doFlash = function () {
            var status
                // Default status messages
              , successStatuses = {
                  create: type + ' created'
                , update: type + ' updated'
                , remove: type + ' removed'
                };

            // User can suppress flashes with {silent: true}
            if(options.silent) {
              return;
            }

            // Find an appropriate flash message
            if(options.status) {
              // Use a user provided status if possible

              this.flash.set(isFailure ? 'error' : 'success', options.status);
            }
            else {

              if(isFailure) {
                this.flash.set('error', content.errors);
              }
              else {
                status = successStatuses[params.action.toLowerCase()];

                // Don't set a flash if no message was found
                if(status) {
                  this.flash.set('success', status);
                }
              }
            }
          };

      // Determine if `content` is a model object
      if (content instanceof model.ModelBase) {

        type = utils.string.getInflection(content.type, 'property', 'singular');

        // Set the flash message
        doFlash.apply(this);

        // Determine if we need to redirect
        redirect = getRedirect.apply(this);

        if (redirect) {
          if (isFailure) {
            this.transfer(redirect.action);
          }
          else {
            this.redirect(redirect);
          }
        }
        else {
          // Respond in the style
          // {model: {attr: val, attr2: val...}, params: {}}
          response = {params: params};
          response[type] = content.toJSON();
          response[type].id = content.id;

          this.respond.call(this, response, options);
        }
      }
      // Determine if `content` is a collection of models
      else if (content instanceof Array) {

        if (content.length) {
          type = content[0].type;
        }
        // If collection is empty, look for something in the options
        // to tell us what this is
        else {
          type = options.type;
        }

        if (!type) {
          throw new Error(
            'Cannot determine model type from empty array, specify one in opts');
        }

        type = utils.string.getInflection(type, 'property', 'plural');

        response = {params: params};
        response[type] = [];

        content.forEach(function (item) {
          response[type].push(item.toJSON());
        });

        this.respond(response, options);
      }
      else if (content instanceof Error) {
        // Format error for template-rendering
        response = utils.mixin({}, content);
        response.message = content.message || '';
        if (geddy.config.detailedErrors) {
          // 'message' and 'stack' are not enumerable
          response.stack = content.stack || '';
        }
        else {
          response.stack = '';
        }
        options.statusCode = content.statusCode || 500;
        this.respond(response, options);
      }
      else {
        throw new Error(
          'respondWith expects either a model, a collection of models, or an Error object');
      }
    };

module.exports = strategy;


text:
package com.whinc.utils;

import com.whinc.model.Word;

/**
 * Created by whinc on 2015/8/20.
 * E-mail: xiaohui_hubei@163.com
 */
public interface Translator {
    String translate(Direction from, Direction to, String source);
    Word queryWord(String word);
}


text:
@interface RSS2Tests : SenTestCase {
    NSArray*    feedUrls;
}

@end


text:
<?php echo $title; ?>

<?php echo $message; ?>


text:
module.exports = function notFound (err) {
    return err && (err.type === 'NotFoundError' || err.message === 'NotFound');
};


text:
'use strict';

import * as Device from 'expo-device';
import { Platform } from 'react-native';

export const name = 'Device';
export async function test(t) {
  t.describe(`Device.getDeviceType()`, () => {
    t.it(`returns enum values`, async () => {
      const deviceType = await Device.getDeviceTypeAsync();
      t.expect(Object.values(Device.DeviceType).includes(deviceType)).toBeTruthy();
    });
  });

  t.describe(`Device.getUptimeAsync()`, () => {
    t.it(`calls getUptimeAsync() and returns number`, async () => {
      const uptime = await Device.getUptimeAsync();
      t.expect(uptime).toBeDefined();
      t.expect(typeof uptime).toEqual('number');
    });
  });

  if (Platform.OS === 'ios') {
    t.describe(`Device on iOS`, () => {
      t.it(`gets most constants and correct types`, async () => {
        const brand = Device.brand;
        const manufacturer = Device.manufacturer;
        const modelName = Device.modelName;
        const osName = Device.osName;
        const totalMemory = Device.totalMemory;
        const isDevice = Device.isDevice;
        const osBuildId = Device.osBuildId;
        const osInternalBuildId = Device.osInternalBuildId;
        const osVersion = Device.osVersion;
        const deviceName = Device.deviceName;
        const deviceYearClass = Device.deviceYearClass;
        t.expect(brand).toBeDefined();
        t.expect(typeof brand).toEqual('string');
        t.expect(manufacturer).toBeDefined();
        t.expect(typeof manufacturer).toEqual('string');
        t.expect(modelName).toBeDefined();
        t.expect(typeof modelName).toEqual('string');
        t.expect(osName).toBeDefined();
        t.expect(typeof osName).toEqual('string');
        t.expect(totalMemory).toBeDefined();
        t.expect(typeof totalMemory).toEqual('number');
        t.expect(isDevice).toBeDefined();
        t.expect(typeof isDevice).toEqual('boolean');
        t.expect(osBuildId).toBeDefined();
        t.expect(typeof osBuildId).toEqual('string');
        t.expect(osInternalBuildId).toBeDefined();
        t.expect(typeof osInternalBuildId).toEqual('string');
        t.expect(osVersion).toBeDefined();
        t.expect(typeof osVersion).toEqual('string');
        t.expect(deviceYearClass).toBeDefined();
        t.expect(typeof deviceYearClass).toEqual('number');
        t.expect(deviceName).toBeDefined();
        t.expect(typeof deviceName).toEqual('string');
      });

      t.it(`doesn't get Android-only constants`, async () => {
        const osBuildFingerprint = Device.osBuildFingerprint;
        const designName = Device.designName;
        const productName = Device.productName;
        const platformApiLevel = Device.platformApiLevel;
        t.expect(designName).toBeNull();
        t.expect(productName).toBeNull();
        t.expect(platformApiLevel).toBeNull();
        t.expect(osBuildFingerprint).toBeNull();
      });

      t.it(`getPlatformFeaturesAsync() returns empty array on iOS`, async () => {
        const allFeatures = await Device.getPlatformFeaturesAsync();
        t.expect(allFeatures).toEqual([]);
      });

      t.it(`hasPlatformFeatureAsync() returns false on iOS`, async () => {
        const hasFeature = await Device.hasPlatformFeatureAsync('amazon_fire_tv');
        t.expect(hasFeature).toEqual(false);
      });

      t.it(`doesn't call getMaxMemoryAsync()`, async () => {
        let error;
        let maxMemory;
        try {
          maxMemory = await Device.getMaxMemoryAsync();
        } catch (e) {
          error = e;
        }
        t.expect(error).toBeDefined();
        t.expect(typeof maxMemory).toEqual('undefined');
      });

      t.it(`doesn't call sideLoadingAsync()`, async () => {
        let error;
        let isSideLoading;
        try {
          isSideLoading = await Device.isSideLoadingEnabledAsync();
        } catch (e) {
          error = e;
        }
        t.expect(error).toBeDefined();
        t.expect(typeof isSideLoading).toEqual('undefined');
      });

      t.it(`gets osBuildId same as osInternalBuildId`, async () => {
        const osBuildId = await Device.osBuildId;
        const osInternalBuildId = await Device.osInternalBuildId;
        t.expect(Device.osBuildId).toBeTruthy();
        t.expect(Device.osInternalBuildId).toBeTruthy();
        t.expect(osBuildId).toEqual(osInternalBuildId);
      });
    });
  } else if (Platform.OS === 'android') {
    t.describe(`Device on Android`, () => {
      t.it(`gets constants and correct types`, async () => {
        const designName = await Device.designName;
        const productName = await Device.productName;
        const brand = await Device.brand;
        const manufacturer = await Device.manufacturer;
        const modelName = await Device.modelName;
        const osName = await Device.osName;
        const totalMemory = await Device.totalMemory;
        const isDevice = await Device.isDevice;
        const osBuildId = await Device.osBuildId;
        const osBuildFingerprint = await Device.osBuildFingerprint;
        const osInternalBuildId = await Device.osInternalBuildId;
        const platformApiLevel = await Device.platformApiLevel;
        const osVersion = await Device.osVersion;
        const deviceName = await Device.deviceName;
        const deviceYearClass = await Device.deviceYearClass;
        t.expect(designName).toBeDefined();
        t.expect(typeof designName).toEqual('string');
        t.expect(productName).toBeDefined();
        t.expect(typeof productName).toEqual('string');
        t.expect(brand).toBeDefined();
        t.expect(typeof brand).toEqual('string');
        t.expect(manufacturer).toBeDefined();
        t.expect(typeof manufacturer).toEqual('string');
        t.expect(modelName).toBeDefined();
        t.expect(typeof modelName).toEqual('string');
        t.expect(osName).toBeDefined();
        t.expect(typeof osName).toEqual('string');
        t.expect(totalMemory).toBeDefined();
        t.expect(typeof totalMemory).toEqual('number');
        t.expect(isDevice).toBeDefined();
        t.expect(typeof isDevice).toEqual('boolean');
        t.expect(osBuildId).toBeDefined();
        t.expect(typeof osBuildId).toEqual('string');
        t.expect(osBuildFingerprint).toBeDefined();
        t.expect(typeof osBuildFingerprint).toEqual('string');
        t.expect(osInternalBuildId).toBeDefined();
        t.expect(typeof osInternalBuildId).toEqual('string');
        t.expect(platformApiLevel).toBeDefined();
        t.expect(typeof platformApiLevel).toEqual('number');
        t.expect(osVersion).toBeDefined();
        t.expect(typeof osVersion).toEqual('string');
        t.expect(deviceYearClass).toBeDefined();
        t.expect(typeof deviceYearClass).toEqual('number');
        if (isDevice) {
          t.expect(deviceName).toBeDefined();
          t.expect(typeof deviceName).toEqual('string');
        } else {
          t.expect(deviceName).toBeNull();
        }
      });

      t.it(`doesn't get modelId`, async () => {
        await Device.modelId;
        t.expect(Device.modelId).toBeNull();
      });

      t.it(`calls hasPlatformFeatureAsync() with valid string and returns boolean`, async () => {
        let error;
        let hasFeature;
        try {
          hasFeature = await Device.hasPlatformFeatureAsync('amazon_fire_tv');
        } catch (e) {
          error = e;
        }
        t.expect(hasFeature).toEqual(t.jasmine.any(Boolean));
        t.expect(error).toBeUndefined();
      });

      t.it(
        `calls hasPlatformFeatureAsync() with invalid string format and returns false`,
        async () => {
          let error;
          let hasFeature;
          try {
            hasFeature = await Device.hasPlatformFeatureAsync('camera');
          } catch (e) {
            error = e;
          }
          t.expect(hasFeature).toEqual(t.jasmine.any(Boolean));
          t.expect(hasFeature).toEqual(false);
          t.expect(error).toBeUndefined();
        }
      );

      t.it(`calls getMaxMemoryAsync() and returns a number under integer limit`, async () => {
        const maxMemory = await Device.getMaxMemoryAsync();
        t.expect(maxMemory).toBeLessThanOrEqual(Number.MAX_SAFE_INTEGER);
      });

      t.it(`calls getPlatformFeaturesAsync()`, async () => {
        const allFeatures = await Device.getPlatformFeaturesAsync();
        t.expect(allFeatures).toBeDefined();
      });
    });
  }
}


text:
package precedence

import "github.com/goby-lang/goby/compiler/token"

// Constants for denoting precedence
const (
	_ = iota
	Lowest
	Normal
	Assign
	Logic
	Range
	Equals
	Compare
	Sum
	Product
	BangPrefix
	Index
	Call
	MinusPrefix
)

// LookupTable maps token to its corresponding precedence
var LookupTable = map[token.Type]int{
	token.Eq:                 Equals,
	token.NotEq:              Equals,
	token.Match:              Compare,
	token.LT:                 Compare,
	token.LTE:                Compare,
	token.GT:                 Compare,
	token.GTE:                Compare,
	token.COMP:               Compare,
	token.And:                Logic,
	token.Or:                 Logic,
	token.Range:              Range,
	token.Plus:               Sum,
	token.Minus:              Sum,
	token.Modulo:             Sum,
	token.Slash:              Product,
	token.Asterisk:           Product,
	token.Pow:                Product,
	token.LBracket:           Index,
	token.Dot:                Call,
	token.LParen:             Call,
	token.ResolutionOperator: Call,
	token.Assign:             Assign,
	token.PlusEq:             Assign,
	token.MinusEq:            Assign,
	token.OrEq:               Assign,
	token.Colon:              Assign,
}