text:
========
Tutorial
========

.. TODO
..
..  - How do I index into arrays or dictionaries?
..  - How do I do array ranges?  e.g. x[5:] or y[2:10]
..  - Blow your mind with macros!
..  - Where's my banana???

Welcome to the Hy tutorial!

In a nutshell, Hy is a Lisp dialect, but one that converts its
structure into Python ... literally a conversion into Python's abstract
syntax tree!  (Or to put it in more crude terms, Hy is lisp-stick on a
Python!)

This is pretty cool because it means Hy is several things:

 - A Lisp that feels very Pythonic
 - For Lispers, a great way to use Lisp's crazy powers but in the wide
   world of Python's libraries (why yes, you now can write a Django
   application in Lisp!)
 - For Pythonistas, a great way to start exploring Lisp, from the
   comfort of Python!
 - For everyone: a pleasant language that has a lot of neat ideas!

Basic intro to Lisp for Pythonistas
===================================

Okay, maybe you've never used Lisp before, but you've used Python!

A "hello world" program in Hy is actually super simple. Let's try it:

.. code-block:: clj

   (print "hello world")

See?  Easy!  As you may have guessed, this is the same as the Python
version of::

  print "hello world"

To add up some super simple math, we could do:

.. code-block:: clj

   (+ 1 3)

Which would return 4 and would be the equivalent of:

.. code-block:: clj

   1 + 3

What you'll notice is that the first item in the list is the function
being called and the rest of the arguments are the arguments being
passed in.  In fact, in Hy (as with most Lisps) we can pass in
multiple arguments to the plus operator:

.. code-block:: clj

   (+ 1 3 55)

Which would return 59.

Maybe you've heard of Lisp before but don't know much about it.  Lisp
isn't as hard as you might think, and Hy inherits from Python, so Hy
is a great way to start learning Lisp.  The main thing that's obvious
about Lisp is that there's a lot of parentheses.  This might seem
confusing at first, but it isn't so hard.  Let's look at some simple
math that's wrapped in a bunch of parentheses that we could enter into
the Hy interpreter:

.. code-block:: clj

   (setv result (- (/ (+ 1 3 88) 2) 8))

This would return 38.  But why?  Well, we could look at the equivalent
expression in python::

  result = ((1 + 3 + 88) / 2) - 8

If you were to try to figure out how the above were to work in python,
you'd of course figure out the results by solving each inner
parenthesis.  That's the same basic idea in Hy.  Let's try this
exercise first in Python::

  result = ((1 + 3 + 88) / 2) - 8
  # simplified to...
  result = (92 / 2) - 8
  # simplified to...
  result = 46 - 8
  # simplified to...
  result = 38

Now let's try the same thing in Hy:

.. code-block:: clj

   (setv result (- (/ (+ 1 3 88) 2) 8))
   ; simplified to...
   (setv result (- (/ 92 2) 8))
   ; simplified to...
   (setv result (- 46 8))
   ; simplified to...
   (setv result 38)

As you probably guessed, this last expression with ``setv`` means to
assign the variable "result" to 38.

See?  Not too hard!

This is the basic premise of Lisp. Lisp stands for "list
processing"; this means that the structure of the program is
actually lists of lists.  (If you're familiar with Python lists,
imagine the entire same structure as above but with square brackets
instead, any you'll be able to see the structure above as both a
program and a data structure.)  This is easier to understand with more
examples, so let's write a simple Python program, test it, and then
show the equivalent Hy program::

  def simple_conversation():
      print "Hello!  I'd like to get to know you.  Tell me about yourself!"
      name = raw_input("What is your name? ")
      age = raw_input("What is your age? ")
      print "Hello " + name + "!  I see you are " + age + " years old."

  simple_conversation()

If we ran this program, it might go like::

  Hello!  I'd like to get to know you.  Tell me about yourself!
  What is your name? Gary
  What is your age? 38
  Hello Gary!  I see you are 38 years old.

Now let's look at the equivalent Hy program:

.. code-block:: clj

   (defn simple-conversation []
      (print "Hello!  I'd like to get to know you.  Tell me about yourself!")
      (setv name (raw-input "What is your name? "))
      (setv age (raw-input "What is your age? "))
      (print (+ "Hello " name "!  I see you are "
                 age " years old.")))

   (simple-conversation)

If you look at the above program, as long as you remember that the
first element in each list of the program is the function (or
macro... we'll get to those later) being called and that the rest are
the arguments, it's pretty easy to figure out what this all means.
(As you probably also guessed, ``defn`` is the Hy method of defining
methods.)

Still, lots of people find this confusing at first because there's so
many parentheses, but there are plenty of things that can help make
this easier: keep indentation nice and use an editor with parenthesis
matching (this will help you figure out what each parenthesis pairs up
with) and things will start to feel comfortable.

There are some advantages to having a code structure that's actually a
very simple data structure as the core of Lisp is based on.  For one
thing, it means that your programs are easy to parse and that the
entire actual structure of the program is very clearly exposed to you.
(There's an extra step in Hy where the structure you see is converted
to Python's own representations ... in "purer" Lisps such as Common
Lisp or Emacs Lisp, the data structure you see in the code and the
data structure that is executed is much more literally close.)

Another implication of this is macros: if a program's structure is a
simple data structure, that means you can write code that can write
code very easily, meaning that implementing entirely new language
features can be very fast.  Previous to Hy, this wasn't very possible
for Python programmers ... now you too can make use of macros'
incredible power (just be careful to not aim them footward)!

Hy is a Lisp-flavored Python
============================

Hy converts to Python's own abstract syntax tree, so you'll soon start
to find that all the familiar power of python is at your fingertips.

You have full access to Python's data types and standard library in
Hy.  Let's experiment with this in the hy interpreter::

  => [1 2 3]
  [1, 2, 3]
  => {"dog" "bark"
  ... "cat" "meow"}
  {'dog': 'bark', 'cat': 'meow'}
  => (, 1 2 3)
  (1, 2, 3)
  => #{3 1 2}
  {1, 2, 3}
  => 1/2
  Fraction(1, 2)

Notice the last two lines: Hy has a fraction literal like Clojure.

If you start Hy like this (a shell alias might be helpful)::

  $ hy --repl-output-fn=hy.contrib.hy-repr.hy-repr

the interactive mode will use :ref:`hy-repr-fn` instead of Python's
native ``repr`` function to print out values, so you'll see values in
Hy syntax rather than Python syntax::

  => [1 2 3]
  [1 2 3]
  => {"dog" "bark"
  ... "cat" "meow"}
  {"dog" "bark" "cat" "meow"}

If you are familiar with other Lisps, you may be interested that Hy
supports the Common Lisp method of quoting:

.. code-block:: clj

   => '(1 2 3)
   (1L 2L 3L)

You also have access to all the built-in types' nice methods::

  => (.strip " fooooo   ")
  "fooooo"

What's this?  Yes indeed, this is precisely the same as::

  " fooooo   ".strip()

That's right---Lisp with dot notation!  If we have this string
assigned as a variable, we can also do the following:

.. code-block:: clj

   (setv this-string " fooooo   ")
   (this-string.strip)

What about conditionals?:

.. code-block:: clj

   (if (try-some-thing)
     (print "this is if true")
     (print "this is if false"))

As you can tell above, the first argument to ``if`` is a truth test, the
second argument is the body if true, and the third argument (optional!)
is if false (ie. ``else``).

If you need to do more complex conditionals, you'll find that you
don't have ``elif`` available in Hy.  Instead, you should use something
called ``cond``.  In Python, you might do something like::

  somevar = 33
  if somevar > 50:
      print "That variable is too big!"
  elif somevar < 10:
      print "That variable is too small!"
  else:
      print "That variable is jussssst right!"

In Hy, you would do:

.. code-block:: clj

   (setv somevar 33)
   (cond
    [(> somevar 50)
     (print "That variable is too big!")]
    [(< somevar 10)
     (print "That variable is too small!")]
    [True
     (print "That variable is jussssst right!")])

What you'll notice is that ``cond`` switches off between a statement
that is executed and checked conditionally for true or falseness, and
then a bit of code to execute if it turns out to be true.  You'll also
notice that the ``else`` is implemented at the end simply by checking
for ``True`` -- that's because ``True`` will always be true, so if we get
this far, we'll always run that one!

You might notice above that if you have code like:

.. code-block:: clj

   (if some-condition
     (body-if-true)
     (body-if-false))

But wait!  What if you want to execute more than one statement in the
body of one of these?

You can do the following:

.. code-block:: clj

   (if (try-some-thing)
     (do
       (print "this is if true")
       (print "and why not, let's keep talking about how true it is!"))
     (print "this one's still simply just false"))

You can see that we used ``do`` to wrap multiple statements.  If you're
familiar with other Lisps, this is the equivalent of ``progn``
elsewhere.

Comments start with semicolons:

.. code-block:: clj

  (print "this will run")
  ; (print "but this will not")
  (+ 1 2 3)  ; we'll execute the addition, but not this comment!

Hashbang (``#!``) syntax is supported:

.. code-block:: clj

   #! /usr/bin/env hy
   (print "Make me executable, and run me!")

Looping is not hard but has a kind of special structure.  In Python,
we might do::

  for i in range(10):
      print "'i' is now at " + str(i)

The equivalent in Hy would be:

.. code-block:: clj

  (for [i (range 10)]
    (print (+ "'i' is now at " (str i))))

You can also import and make use of various Python libraries.  For
example:

.. code-block:: clj

   (import os)

   (if (os.path.isdir "/tmp/somedir")
     (os.mkdir "/tmp/somedir/anotherdir")
     (print "Hey, that path isn't there!"))

Python's context managers (``with`` statements) are used like this:

.. code-block:: clj

     (with [f (open "/tmp/data.in")]
       (print (.read f)))

which is equivalent to::

  with open("/tmp/data.in") as f:
      print f.read()

And yes, we do have List comprehensions!  In Python you might do::

  odds_squared = [
    pow(num, 2)
    for num in range(100)
    if num % 2 == 1]

In Hy, you could do these like:

.. code-block:: clj

  (setv odds-squared
    (list-comp
      (pow num 2)
      (num (range 100))
      (= (% num 2) 1)))

.. code-block:: clj

  ; And, an example stolen shamelessly from a Clojure page:
  ; Let's list all the blocks of a Chessboard:

  (list-comp
    (, x y)
    (x (range 8)
     y "ABCDEFGH"))

  ; [(0, 'A'), (0, 'B'), (0, 'C'), (0, 'D'), (0, 'E'), (0, 'F'), (0, 'G'), (0, 'H'),
  ;  (1, 'A'), (1, 'B'), (1, 'C'), (1, 'D'), (1, 'E'), (1, 'F'), (1, 'G'), (1, 'H'),
  ;  (2, 'A'), (2, 'B'), (2, 'C'), (2, 'D'), (2, 'E'), (2, 'F'), (2, 'G'), (2, 'H'),
  ;  (3, 'A'), (3, 'B'), (3, 'C'), (3, 'D'), (3, 'E'), (3, 'F'), (3, 'G'), (3, 'H'),
  ;  (4, 'A'), (4, 'B'), (4, 'C'), (4, 'D'), (4, 'E'), (4, 'F'), (4, 'G'), (4, 'H'),
  ;  (5, 'A'), (5, 'B'), (5, 'C'), (5, 'D'), (5, 'E'), (5, 'F'), (5, 'G'), (5, 'H'),
  ;  (6, 'A'), (6, 'B'), (6, 'C'), (6, 'D'), (6, 'E'), (6, 'F'), (6, 'G'), (6, 'H'),
  ;  (7, 'A'), (7, 'B'), (7, 'C'), (7, 'D'), (7, 'E'), (7, 'F'), (7, 'G'), (7, 'H')]

Python has support for various fancy argument and keyword arguments.
In Python we might see::

  >>> def optional_arg(pos1, pos2, keyword1=None, keyword2=42):
  ...   return [pos1, pos2, keyword1, keyword2]
  ...
  >>> optional_arg(1, 2)
  [1, 2, None, 42]
  >>> optional_arg(1, 2, 3, 4)
  [1, 2, 3, 4]
  >>> optional_arg(keyword1=1, pos2=2, pos1=3, keyword2=4)
  [3, 2, 1, 4]

The same thing in Hy::

  => (defn optional-arg [pos1 pos2 &optional keyword1 [keyword2 42]]
  ...  [pos1 pos2 keyword1 keyword2])
  => (optional-arg 1 2)
  [1 2 None 42]
  => (optional-arg 1 2 3 4)
  [1 2 3 4]

If you're running a version of Hy past 0.10.1 (eg, git master),
there's also a nice new keyword argument syntax::

  => (optional-arg :keyword1 1
  ...              :pos2 2
  ...              :pos1 3
  ...              :keyword2 4)
  [3, 2, 1, 4]

Otherwise, you can always use `apply`.  But what's `apply`?

Are you familiar with passing in `*args` and `**kwargs` in Python?::

  >>> args = [1 2]
  >>> kwargs = {"keyword2": 3
  ...           "keyword1": 4}
  >>> optional_arg(*args, **kwargs)

We can reproduce this with `apply`::

  => (setv args [1 2])
  => (setv kwargs {"keyword2" 3
  ...              "keyword1" 4})
  => (apply optional-arg args kwargs)
  [1, 2, 4, 3]

There's also a dictionary-style keyword arguments construction that
looks like:

.. code-block:: clj

  (defn another-style [&key {"key1" "val1" "key2" "val2"}]
    [key1 key2])

The difference here is that since it's a dictionary, you can't rely on
any specific ordering to the arguments.

Hy also supports ``*args`` and ``**kwargs``.  In Python::

  def some_func(foo, bar, *args, **kwargs):
    import pprint
    pprint.pprint((foo, bar, args, kwargs))

The Hy equivalent:

.. code-block:: clj

  (defn some-func [foo bar &rest args &kwargs kwargs]
    (import pprint)
    (pprint.pprint (, foo bar args kwargs)))

Finally, of course we need classes!  In Python, we might have a class
like::

  class FooBar(object):
      """
      Yet Another Example Class
      """
      def __init__(self, x):
          self.x = x

      def get_x(self):
          """
          Return our copy of x
          """
          return self.x

And we might use it like::

  bar = FooBar(1)
  print bar.get_x()

In Hy:

.. code-block:: clj

  (defclass FooBar [object]
    "Yet Another Example Class"

    (defn --init-- [self x]
      (setv self.x x))

    (defn get-x [self]
      "Return our copy of x"
      self.x))

And we can use it like:

.. code-block:: clj

  (setv bar (FooBar 1))
  (print (bar.get-x))

Or using the leading dot syntax!

.. code-block:: clj

  (print (.get-x (FooBar 1)))

You can also do class-level attributes.  In Python::

  class Customer(models.Model):
      name = models.CharField(max_length=255)
      address = models.TextField()
      notes = models.TextField()

In Hy:

.. code-block:: clj

  (defclass Customer [models.Model]
    [name (models.CharField :max-length 255})
     address (models.TextField)
     notes (models.TextField)])

Macros
======

One really powerful feature of Hy are macros. They are small functions that are
used to generate code (or data). When program written in Hy is started, the
macros are executed and their output is placed in the program source. After this,
the program starts executing normally. Very simple example:

.. code-block:: clj

  => (defmacro hello [person]
  ...  `(print "Hello there," ~person))
  => (hello "Tuukka")
  Hello there, Tuukka

The thing to notice here is that hello macro doesn't output anything on
screen. Instead it creates piece of code that is then executed and prints on
screen. This macro writes a piece of program that looks like this (provided that
we used "Tuukka" as parameter):

.. code-block:: clj

  (print "Hello there," "Tuukka")

We can also manipulate code with macros:

.. code-block:: clj

  => (defmacro rev [code]
  ...  (setv op (last code) params (list (butlast code)))
  ...  `(~op ~@params))
  => (rev (1 2 3 +))
  6

The code that was generated with this macro just switched around some of the
elements, so by the time program started executing, it actually reads:

.. code-block:: clj

  (+ 1 2 3)

Sometimes it's nice to be able to call a one-parameter macro without
parentheses. Sharp macros allow this. The name of a sharp macro must be only
one character long, but since Hy operates well with Unicode, we aren't running
out of characters that soon:

.. code-block:: clj

  => (defsharp ↻ [code]
  ...  (setv op (last code) params (list (butlast code)))
  ...  `(~op ~@params))
  => #↻(1 2 3 +)
  6

Macros are useful when one wishes to extend Hy or write their own
language on top of that. Many features of Hy are macros, like ``when``,
``cond`` and ``->``.

What if you want to use a macro that's defined in a different
module? The special form ``import`` won't help, because it merely
translates to a Python ``import`` statement that's executed at
run-time, and macros are expanded at compile-time, that is,
during the translate from Hy to Python. Instead, use ``require``,
which imports the module and makes macros available at
compile-time. ``require`` uses the same syntax as ``import``.

.. code-block:: clj

   => (require tutorial.macros)
   => (tutorial.macros.rev (1 2 3 +))
   6

Hy <-> Python interop
=====================

Using Hy from Python
--------------------

You can use Hy modules in Python!

If you save the following in ``greetings.hy``:

.. code-block:: clj

    (defn greet [name] (print "hello from hy," name))

Then you can use it directly from Python, by importing Hy before importing
the module. In Python::

    import hy
    import greetings

    greetings.greet("Foo")

Using Python from Hy
--------------------

You can also use any Python module in Hy!

If you save the following in ``greetings.py`` in Python::

    def greet(name):
        print("hello, %s" % (name))

You can use it in Hy (see :ref:`import`):

.. code-block:: clj

    (import greetings)
    (.greet greetings "foo")

More information on :doc:`../language/interop`.

Protips!
========

Hy also features something known as the "threading macro", a really neat
feature of Clojure's. The "threading macro" (written as ``->``) is used
to avoid deep nesting of expressions.

The threading macro inserts each expression into the next expression's first
argument place.

Let's take the classic:

.. code-block:: clj

    (loop (print (eval (read))))

Rather than write it like that, we can write it as follows:

.. code-block:: clj

    (-> (read) (eval) (print) (loop))

Now, using `python-sh <http://amoffat.github.com/sh/>`_, we can show
how the threading macro (because of python-sh's setup) can be used like
a pipe:

.. code-block:: clj

    => (import [sh [cat grep wc]])
    => (-> (cat "/usr/share/dict/words") (grep "-E" "^hy") (wc "-l"))
    210

Which, of course, expands out to:

.. code-block:: clj

    (wc (grep (cat "/usr/share/dict/words") "-E" "^hy") "-l")

Much more readable, no? Use the threading macro!


text:
<?php

Route::group(['prefix' => 'customer', 'namespace' => 'Modules\Customer\Http\Controllers'], function()
{
	Route::get('/', 'CustomerController@index');
});

redpajama_set_name: RedPajamaGithub


text:
<#
    .DESCRIPTION
        This example shows how to ensure that the server role named
        AdminSqlforBI is present on instance sqltest.company.local\DSC and only logins
        CONTOSO\SQLAdmin and CONTOSO\SQLAdminBI are members of this role.
#>

Configuration Example
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SqlAdministratorCredential
    )

    Import-DscResource -ModuleName 'SqlServerDsc'

    node localhost
    {
        SqlRole 'Add_ServerRole_AdminSqlforBI'
        {
            Ensure               = 'Present'
            ServerRoleName       = 'AdminSqlforBI'
            Members              = 'CONTOSO\SQLAdmin', 'CONTOSO\SQLAdminBI'
            ServerName           = 'sqltest.company.local'
            InstanceName         = 'DSC'

            PsDscRunAsCredential = $SqlAdministratorCredential
        }
    }
}


text:
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('body', function(Y, NAME) {

/**
 * The body module.
 *
 * @module body
 */
    /**
     * Constructor for the Controller class.
     *
     * @class Controller
     * @constructor
     */
    Y.namespace('mojito.controllers')[NAME] = {

        /**
         * Method corresponding to the 'index' action.
         *
         * @param ac {Object} The ActionContext that provides access
         *        to the Mojito API.
         */
        index: function(ac) {
            var view_type = ac.params.getFromRoute('view_type') || "yui";
            if (view_type === "yui") {
                ac.composite.done({
                    title: ""
                });
            } else if (view_type === "mojito") {
                ac.composite.done({
                    title: ""
                }, {"view": {"name": "mojito"}});
            }
        }
    };
}, '0.0.1', {requires: ['mojito','mojito-composite-addon', 'mojito-params-addon']});


text:
package com.maddyhome.idea.copyright.language.psi;

import com.intellij.lang.Language;
import com.intellij.psi.tree.IElementType;
import com.maddyhome.idea.copyright.language.SimpleLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Created by mike on 9/6/15.
 */
public class SimpleElementType extends IElementType {
  public SimpleElementType(@NotNull @NonNls String debugName) {
    super(debugName, SimpleLanguage.INSTANCE);
  }
}


text:
; =============================================================================
; Pure64 MBR -- a 64-bit OS loader written in Assembly for x86-64 systems
; Copyright (C) 2008-2015 Return Infinity -- see LICENSE.TXT
;
; This Master Boot Record will load Pure64 from a pre-defined location on the
; hard drive without making use of the file system.
;
; In this code we are expecting a BMFS-formatted drive. With BMFS the Pure64
; binary is required to start at sector 16 (8192 bytes from the start). A small
; ckeck is made to make sure Pure64 was loaded by comparing a signiture.
; =============================================================================

USE16
org 0x7C00

entry:
	cli				; Disable interrupts
;	xchg bx, bx			; Bochs magic debug
	xor eax, eax
	mov ss, ax
	mov es, ax
	mov ds, ax
	mov sp, 0x7C00
	sti				; Enable interrupts

	mov [DriveNumber], dl		; BIOS passes drive number in DL

	mov si, msg_Load
	call print_string_16

	mov eax, 64			; Number of sectors to load. 64 sectors = 32768 bytes
	mov ebx, 16			; Start immediately after directory (offset 8192)
	mov cx, 0x8000			; Pure64 expects to be loaded at 0x8000

load_nextsector:
	call readsector			; Load 512 bytes
	dec eax
	cmp eax, 0
	jnz load_nextsector

	mov eax, [0x8000]
	cmp eax, 0xC03166FA		; Match against the Pure64 binary
	jne magic_fail

	mov si, msg_LoadDone
	call print_string_16

	jmp 0x0000:0x8000

magic_fail:
	mov si, msg_MagicFail
	call print_string_16
halt:
	hlt
	jmp halt

;------------------------------------------------------------------------------
; Read a sector from a disk, using LBA
; IN:	EAX - High word of 64-bit DOS sector number
;	EBX - Low word of 64-bit DOS sector number
;	ES:CX - destination buffer
; OUT:	ES:CX points one byte after the last byte read
;	EAX - High word of next sector
;	EBX - Low word of sector
readsector:
	push eax
	xor eax, eax			; We don't need to load from sectors > 32-bit
	push dx
	push si
	push di

read_it:
	push eax			; Save the sector number
	push ebx
	mov di, sp			; remember parameter block end

	push eax			; [C] sector number high 32bit
	push ebx			; [8] sector number low 32bit
	push es				; [6] buffer segment
	push cx				; [4] buffer offset
	push byte 1			; [2] 1 sector (word)
	push byte 16			; [0] size of parameter block (word)

	mov si, sp
	mov dl, [DriveNumber]
	mov ah, 42h			; EXTENDED READ
	int 0x13			; http://hdebruijn.soo.dto.tudelft.nl/newpage/interupt/out-0700.htm#0651

	mov sp, di			; remove parameter block from stack
	pop ebx
	pop eax				; Restore the sector number

	jnc read_ok			; jump if no error

	push ax
	xor ah, ah			; else, reset and retry
	int 0x13
	pop ax
	jmp read_it

read_ok:
	add ebx, 1			; increment next sector with carry
	adc eax, 0
	add cx, 512			; Add bytes per sector
	jnc no_incr_es			; if overflow...

incr_es:
	mov dx, es
	add dh, 0x10			; ...add 1000h to ES
	mov es, dx

no_incr_es:
	pop di
	pop si
	pop dx
	pop eax

	ret
;------------------------------------------------------------------------------

;------------------------------------------------------------------------------
; 16-bit function to print a string to the screen
; IN:	SI - Address of start of string
print_string_16:			; Output string in SI to screen
	pusha
	mov ah, 0x0E			; int 0x10 teletype function
.repeat:
	lodsb				; Get char from string
	cmp al, 0
	je .done			; If char is zero, end of string
	int 0x10			; Otherwise, print it
	jmp short .repeat
.done:
	popa
	ret
;------------------------------------------------------------------------------

msg_Load db "BMFS MBR v1.0 - Loading Pure64", 0
msg_LoadDone db " - done.", 13, 10, "Executing...", 0
msg_MagicFail db " - Not found!", 0
DriveNumber db 0x00

times 446-$+$$ db 0

; False partition table entry required by some BIOS vendors.
db 0x80, 0x00, 0x01, 0x00, 0xEB, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF

times 510-$+$$ db 0

sign dw 0xAA55


text:
package com.andrewreitz.ircbot;

import com.andrewreitz.ircbot.config.Config;
import com.google.common.base.Strings;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.reactivex.netty.RxNetty;
import io.reactivex.netty.client.RxClient;
import io.reactivex.netty.pipeline.PipelineConfigurators;
import rx.Observable;

import static com.andrewreitz.ircbot.IrcClient.Command.JOIN;
import static com.andrewreitz.ircbot.IrcClient.Command.NICK;
import static com.andrewreitz.ircbot.IrcClient.Command.PING;
import static com.andrewreitz.ircbot.IrcClient.Command.PONG;
import static com.andrewreitz.ircbot.IrcClient.Command.PRIVMSG;
import static com.andrewreitz.ircbot.IrcClient.Command.USER;

public class IrcClient {
  /** Messages can't be longer than 512 */
  private static final int MESSAGE_LENGTH = 512;

  enum Command {
    NICK("NICK %s\n\r"),
    USER("USER %s 8 * :%s\r\n"),
    JOIN("JOIN #%s\n\r"),
    PING(""),
    PONG("PONG %s\n\r"),
    PRIVMSG("PRIVMSG #%s :%s\n\r");

    final String command;

    private Command(String command) {
      this.command = command;
    }
  }

  private final Logger logger = LoggerFactory.getLogger(IrcClient.class);

  private final Config config;
  private final CommandParser commandParser;
  private final RxClient<String, String> client;

  public IrcClient(Config config, CommandParser commandParser) {
    this.config = config;
    this.commandParser = commandParser;

    client = RxNetty.createTcpClient(config.getServer(), config.getPort(),
        PipelineConfigurators.textOnlyConfigurator());
  }

  public void start() {
    logger.debug("Connecting to {}:{}", config.getServer(), config.getPort());

    Iterable<String> messages = client.connect()
        .flatMap(connection -> {

          Observable<String> nickCommand = connection.writeAndFlush(createMessage(NICK, config.getNick()))
              .map(aVoid -> {
                logger.debug("Setting NICK to {}", config.getNick());
                return "";
              });

          Observable<String> userCommand = connection.writeAndFlush(
              createMessage(USER, config.getUsername(), config.getFullname()))
              .map(aVoid -> {
                logger.debug("Setting user");
                return "";
              });

          Observable<String> joinCommand = connection.writeAndFlush(
              createMessage(JOIN, config.getChannel()))
              .map(aVoid -> {
                logger.debug("Joining channel {}", config.getChannel());
                return "";
              });

          Observable<String> fromServer = connection.getInput()
              .map(s -> {
                s = s.trim();
                if (s.startsWith(PING.name())) {
                  String[] messageChunks = s.replace(":", "").split(" ");
                  String server = messageChunks[messageChunks.length - 1];
                  connection.writeAndFlush(createMessage(PONG, server))
                      .subscribe(aVoid -> logger.debug("Sending PONG to server"));
                }

                if (s.contains(PRIVMSG.name())) {
                  String message = s.substring(s.lastIndexOf(":") + 1);
                  String response = commandParser.parseMessage(message);
                  if (!Strings.isNullOrEmpty(response)) {
                    for (int i = 0, len = response.length(); i < len; i += MESSAGE_LENGTH) {
                      int end = Math.min(len, i + MESSAGE_LENGTH);
                      String responseChunk = response.substring(i, end);
                      connection.writeAndFlush(createMessage(PRIVMSG, config.getChannel(),
                          responseChunk))
                          .subscribe(aVoid -> logger.debug("Sending message {}", response));
                    }
                  }
                }

                return s;
              });

          return Observable.merge(Observable.concat(nickCommand, userCommand, joinCommand), fromServer);
        })
        .toBlocking()
        .toIterable();

    for (String message : messages) {
      System.out.println(message);
    }
  }

  private static String createMessage(Command command, Object... args) {
    return String.format(command.command, args);
  }
}


text:
<?php

include("Mysql.php");

Class finances
{

/*	private $newMysql;
	private $connect;

	public function __construct(newMysql $newMysql, connect $connect)
	{
		$newMysql = new MySQL();
		$connect = $newMysql->connect();

	} */

	public function getYearTotals($year)
	{
		$connect = mysqli_connect("localhost", "higgins", "higgins", "TSP_v_1.0.0");

		$result = mysqli_query($connect, "SELECT * FROM income WHERE YEAR(timestamp) = '".$year."'");

		$chart_data = array();

		$i = 0;

		while($row = mysqli_fetch_array($result))
		{
			$chart_data[$i]['recieved'] = $row["recieved_amt"];
			$chart_data[$i]['tax'] = $row["tax"];
			$chart_data[$i]['income'] = $row["final_amt"];
			$chart_data[$i]['transaction_ID'] = $row["in_trans_ID"];
			$chart_data[$i]['date'] = $row["timestamp"];
			$chart_data[$i]['first_name'] = $row["client_fname"];
			$chart_data[$i]['last_name'] = $row["client_lname"];
			$i++;
		}
		print json_encode($chart_data);
	}

	public function getMonthTotals($month)
	{
		$connect = mysqli_connect("localhost", "higgins", "higgins", "TSP_v_1.0.0");

		$result = mysqli_query($connect, "SELECT * FROM income WHERE MONTH(timestamp) = '".$month."'");

		$chart_data = array();

		$i = 0;

		while($row = mysqli_fetch_array($result))
		{
			$chart_data[$i]['recieved'] = $row["recieved_amt"];
			$chart_data[$i]['tax'] = $row["tax"];
			$chart_data[$i]['income'] = $row["final_amt"];
			$chart_data[$i]['transaction_ID'] = $row["in_trans_ID"];
			$chart_data[$i]['date'] = $row["timestamp"];
			$chart_data[$i]['first_name'] = $row["client_fname"];
			$chart_data[$i]['last_name'] = $row["client_lname"];
			$i++;
		}
		print json_encode($chart_data);
	}

}


text:
class Seeder
  def seed_admins
    seeding "admins"
    clear_table "admins"
    admin = Admin.new({
        :first_name => "admin",
        :last_name => "admin",
        :email => ENV["email_contact"].dup, # Dup to avoid a Devise error…
        :admin => true,
    })
    admin.password = admin.password_confirmation = random_string
    #admin.confirm!
    say "admin: #{admin.email} => #{admin.password}"
    admin.save!
  end

private
  def random_string(length = 16)
    a = [(0..9), ('a'..'z'), ('A'..'Z')].map { |x| x.to_a }.flatten
    (0...length).map { a[rand(a.length)] }.join
  end
end


text:
/**
 *
 */
package net.i2geo.comped.service;

import java.util.List;

import org.appfuse.service.GenericManager;
import net.i2geo.comped.model.Name;
import net.i2geo.comped.model.Nameable;
import net.i2geo.comped.model.Thing;

/**
 * @author Martin Homik
 *
 */
public interface NameManager extends GenericManager<Name, Long> {

	public List<Name> getNames(Nameable nameable);
	public List<Name> findByNameExact(String name);
	public List<Name> findByNameLike(String name);
	public List<Name> getByLocale(String locale);
	public List<Name> findByNameAndLocaleExact(String name, String locale);
	public List<Name> findByNameAndLocaleLike(String name, String locale);
	public List<Name> findByType(String type);
	public List<Name> findByTypeAndLocale(String type, String locale);
	public List<Name> findByThing(Thing thing);
	public List<Name> findByThingAndType(Thing thing, String type);
	public List<Name> findByThingAndTypeAndLocale(Thing thing, String type, String locale);
	public Name       findDefaultByThingAndTypeAndLocale(Nameable nameable, String type, String locale);

	public void detach(Name name);

}


text:
class VMClassRegistry;
class BGSSoundDescriptorForm;
class TESObjectTREE;
class TESForm;

namespace papyrusTree
{
	void RegisterFuncs(VMClassRegistry* registry);

	TESForm * GetIngredient(TESObjectTREE* thisTree);
	void SetIngredient(TESObjectTREE* thisTree, TESForm* ingredient);

	BGSSoundDescriptorForm * GetHarvestSound(TESObjectTREE* thisTree);
	void SetHarvestSound(TESObjectTREE* thisTree, BGSSoundDescriptorForm * sound);
};


text:
ALTER TABLE events DROP CONSTRAINT event_id_pk;
ALTER TABLE events RENAME TO events_001;

-- Now create the new table (copy-and-pasted from table-def.sql)
CREATE TABLE events (
	-- App
	app_id varchar(255) encode text255,
	platform varchar(255) encode text255,
	-- Date/time
	collector_tstamp timestamp not null,
	dvce_tstamp timestamp,
	-- Event
	event varchar(128) encode text255,
	event_vendor varchar(128) encode text32k not null,
	event_id varchar(38) not null unique,
	txn_id int,
	-- Versioning
	v_tracker varchar(100) encode text255,
	v_collector varchar(100) encode text255 not null,
	v_etl varchar(100) encode text255 not null,
	-- User and visit
	user_id varchar(255) encode runlength,
	user_ipaddress varchar(19) encode runlength,
	user_fingerprint varchar(50) encode runlength,
	domain_userid varchar(16),
	domain_sessionidx smallint,
	network_userid varchar(38),
	-- Page
	page_title varchar(2000),
	-- Page URL components
	page_urlscheme varchar(16) encode text255,
	page_urlhost varchar(255) encode text255,
	page_urlport smallint,
	page_urlpath varchar(1000) encode text32k,
	page_urlquery varchar(3000),
	page_urlfragment varchar(255),
	-- Referrer URL components
	refr_urlscheme varchar(16) encode text255,
	refr_urlhost varchar(255) encode text255,
	refr_urlport smallint,
	refr_urlpath varchar(1000) encode text32k,
	refr_urlquery varchar(3000),
	refr_urlfragment varchar(255),
	-- Referrer details
	refr_medium varchar(25) encode text255,
	refr_source varchar(50) encode text255,
	refr_term varchar(255) encode raw,
	-- Marketing
	mkt_medium varchar(255) encode text255,
	mkt_source varchar(255) encode text255,
	mkt_term varchar(255) encode raw,
	mkt_content varchar(500) encode raw,
	mkt_campaign varchar(255) encode text32k,
	-- Custom Event
	ev_category varchar(255) encode text255,
	ev_action varchar(255) encode text255,
	ev_label varchar(255) encode text32k,
	ev_property varchar(255) encode text32k,
	ev_value float,
	-- Ecommerce
	tr_orderid varchar(255) encode raw,
	tr_affiliation varchar(255) encode text255,
	tr_total dec(18,2),
	tr_tax dec(18,2),
	tr_shipping dec(18,2),
	tr_city varchar(255) encode text32k,
	tr_state varchar(255) encode text32k,
	tr_country varchar(255) encode text32k,
	ti_orderid varchar(255) encode raw,
	ti_sku varchar(255) encode text32k,
	ti_name varchar(255) encode text32k,
	ti_category varchar(255) encode text255,
	ti_price dec(18,2),
	ti_quantity int,
	-- Page ping
	pp_xoffset_min integer,
	pp_xoffset_max integer,
	pp_yoffset_min integer,
	pp_yoffset_max integer,
	-- User Agent
	useragent varchar(1000) encode text32k,
	-- Browser
	br_name varchar(50) encode text255,
	br_family varchar(50) encode text255,
	br_version varchar(50) encode text255,
	br_type varchar(50) encode text255,
	br_renderengine varchar(50) encode text255,
	br_lang varchar(255) encode text255,
	br_features_pdf boolean,
	br_features_flash boolean,
	br_features_java boolean,
	br_features_director boolean,
	br_features_quicktime boolean,
	br_features_realplayer boolean,
	br_features_windowsmedia boolean,
	br_features_gears boolean ,
	br_features_silverlight boolean,
	br_cookies boolean,
	br_colordepth varchar(12) encode text255,
	br_viewwidth integer,
	br_viewheight integer,
	-- Operating System
	os_name varchar(50) encode text255,
	os_family varchar(50)  encode text255,
	os_manufacturer varchar(50)  encode text255,
	os_timezone varchar(255)  encode text255,
	-- Device/Hardware
	dvce_type varchar(50)  encode text255,
	dvce_ismobile boolean,
	dvce_screenwidth integer,
	dvce_screenheight integer,
	-- Document
	doc_charset varchar(128) encode text255,
	doc_width integer,
	doc_height integer,
	CONSTRAINT event_id_pk PRIMARY KEY(event_id)
)
DISTSTYLE KEY
DISTKEY (domain_userid)
SORTKEY (collector_tstamp);

-- Finally copy all the old data into the new format
INSERT INTO events
	SELECT
	-- App
	app_id,
	platform,
	-- Date/time
	collector_tstamp,
	dvce_tstamp,
	-- Event
	event,
	event_vendor,
	event_id,
	txn_id,
	-- Versioning
	v_tracker,
	v_collector,
	v_etl,
	-- User and visit
	user_id,
	user_ipaddress,
	user_fingerprint,
	domain_userid,
	domain_sessionidx,
	network_userid,
	-- Page
	page_title,
	                          -- Don't select page_referrer
	-- Page URL components
	page_urlscheme,
	page_urlhost,
	page_urlport,
	page_urlpath,
	page_urlquery,
	page_urlfragment,
	-- Referrer URL components
	null AS refr_urlscheme,   -- Placeholder
	null AS refr_urlhost,     -- Placeholder
	null AS refr_urlport,     -- Placeholder
	null AS refr_urlpath,     -- Placeholder
	null AS refr_urlquery,    -- Placeholder
	null AS refr_urlfragment, -- Placeholder
	-- Referrer details
	null AS refr_medium,      -- Placeholder
	null AS refr_source,      -- Placeholder
	null AS refr_term,        -- Placeholder
	-- Marketing
	mkt_source AS mkt_medium, -- Swap to fix #215
	mkt_medium AS mkt_source, -- Swap to fix #215
	mkt_term,
	mkt_content,
	mkt_campaign,
	-- Custom Event
	ev_category,
	ev_action,
	ev_label,
	ev_property,
	ev_value,
	-- Ecommerce
	tr_orderid,
	tr_affiliation,
	tr_total,
	tr_tax,
	tr_shipping,
	tr_city,
	tr_state,
	tr_country,
	ti_orderid,
	ti_sku,
	ti_name,
	ti_category,
	ti_price,
	ti_quantity,
	-- Page ping
	pp_xoffset_min,
	pp_xoffset_max,
	pp_yoffset_min,
	pp_yoffset_max,
	-- User Agent
	useragent,
	-- Browser
	br_name,
	br_family,
	br_version,
	br_type,
	br_renderengine,
	br_lang,
	br_features_pdf,
	br_features_flash,
	br_features_java,
	br_features_director,
	br_features_quicktime,
	br_features_realplayer,
	br_features_windowsmedia,
	br_features_gears,
	br_features_silverlight,
	br_cookies,
	br_colordepth,
	br_viewwidth,
	br_viewheight,
	-- Operating System
	os_name,
	os_family,
	os_manufacturer,
	os_timezone,
	-- Device/Hardware
	dvce_type,
	dvce_ismobile,
	dvce_screenwidth,
	dvce_screenheight,
	-- Document
	doc_charset,
	doc_width,
	doc_height
FROM events_001;


text:
/**
 * Blocker game
 */

const boot = require('./blocker/boot')
const load = require('./blocker/load')
const play = require('./blocker/play')

module.exports = {
  Boot: boot,
  Load: load,
  Play: play
}


text:
<?php

namespace Illuminate\Tests\Integration\Database\EloquentCollectionLoadMissingTest;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;

/**
 * @group integration
 */
class EloquentCollectionLoadMissingTest extends DatabaseTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('parent_id')->nullable();
            $table->unsignedInteger('post_id');
        });

        Schema::create('revisions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('comment_id');
        });

        Schema::create('post_relations', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('post_id');
        });

        Schema::create('post_sub_relations', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('post_relation_id');
        });

        Schema::create('post_sub_sub_relations', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('post_sub_relation_id');
        });

        User::create();

        Post::create(['user_id' => 1]);

        Comment::create(['parent_id' => null, 'post_id' => 1]);
        Comment::create(['parent_id' => 1, 'post_id' => 1]);
        Comment::create(['parent_id' => 2, 'post_id' => 1]);

        Revision::create(['comment_id' => 1]);

        Post::create(['user_id' => 1]);
        PostRelation::create(['post_id' => 2]);
        PostSubRelation::create(['post_relation_id' => 1]);
        PostSubSubRelation::create(['post_sub_relation_id' => 1]);
    }

    public function testLoadMissing()
    {
        $posts = Post::with('comments', 'user')->get();

        DB::enableQueryLog();

        $posts->loadMissing('comments.parent.revisions:revisions.comment_id', 'user:id');

        $this->assertCount(2, DB::getQueryLog());
        $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent'));
        $this->assertTrue($posts[0]->comments[1]->parent->relationLoaded('revisions'));
        $this->assertArrayNotHasKey('id', $posts[0]->comments[1]->parent->revisions[0]->getAttributes());
    }

    public function testLoadMissingWithClosure()
    {
        $posts = Post::with('comments')->get();

        DB::enableQueryLog();

        $posts->loadMissing(['comments.parent' => function ($query) {
            $query->select('id');
        }]);

        $this->assertCount(1, DB::getQueryLog());
        $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent'));
        $this->assertArrayNotHasKey('post_id', $posts[0]->comments[1]->parent->getAttributes());
    }

    public function testLoadMissingWithDuplicateRelationName()
    {
        $posts = Post::with('comments')->get();

        DB::enableQueryLog();

        $posts->loadMissing('comments.parent.parent');

        $this->assertCount(2, DB::getQueryLog());
        $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent'));
        $this->assertTrue($posts[0]->comments[1]->parent->relationLoaded('parent'));
    }

    public function testLoadMissingWithoutInitialLoad()
    {
        $user = User::first();
        $user->loadMissing('posts.postRelation.postSubRelations.postSubSubRelations');

        $this->assertEquals(2, $user->posts->count());
        $this->assertNull($user->posts[0]->postRelation);
        $this->assertInstanceOf(PostRelation::class, $user->posts[1]->postRelation);
        $this->assertEquals(1, $user->posts[1]->postRelation->postSubRelations->count());
        $this->assertInstanceOf(PostSubRelation::class, $user->posts[1]->postRelation->postSubRelations[0]);
        $this->assertEquals(1, $user->posts[1]->postRelation->postSubRelations[0]->postSubSubRelations->count());
        $this->assertInstanceOf(PostSubSubRelation::class, $user->posts[1]->postRelation->postSubRelations[0]->postSubSubRelations[0]);
    }
}

class Comment extends Model
{
    public $timestamps = false;

    protected $guarded = [];

    public function parent()
    {
        return $this->belongsTo(self::class);
    }

    public function revisions()
    {
        return $this->hasMany(Revision::class);
    }
}

class Post extends Model
{
    public $timestamps = false;

    protected $guarded = [];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function postRelation()
    {
        return $this->hasOne(PostRelation::class);
    }
}

class PostRelation extends Model
{
    public $timestamps = false;

    protected $guarded = [];

    public function postSubRelations()
    {
        return $this->hasMany(PostSubRelation::class);
    }
}

class PostSubRelation extends Model
{
    public $timestamps = false;

    protected $guarded = [];

    public function postSubSubRelations()
    {
        return $this->hasMany(PostSubSubRelation::class);
    }
}

class PostSubSubRelation extends Model
{
    public $timestamps = false;

    protected $guarded = [];
}

class Revision extends Model
{
    public $timestamps = false;

    protected $guarded = [];
}

class User extends Model
{
    public $timestamps = false;

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}


text:
layout: post
title: "Implementing localization in ASP.NET Core"
subtitle: "This post is about implementing localization in ASP.NET Core. Localization is the process of adapting a globalized app, which you have already processed for localizability, to a particular culture/locale. Localization is one of the best practise in web application development."
date: 2017-05-08 00:00:00
categories: [ASP.NET Core, Localization]
tags: [ASP.NET Core, Localization]
author: "Anuraj"
---
This post is about implementing localization in ASP.NET Core. Localization is the process of adapting a globalized app, which you have already processed for localizability, to a particular culture/locale. Localization is one of the best practise in web application development.

Similar to earlier versions of ASP.NET, ASP.NET Core also supports resource file based localization. You can create various resource files (*.resx) based on the supported languages and configure ASP.NET Core to load resources based on the various parameters, like query string, cookies, headers etc.

First you need to create resource files for the languages you want to support and the naming should be based on the classes or views you want to localize. For example, if you want to localize all the strings in `HomeController` class in US English and UK English, you need to create resource files with the name `HomeController.en-US.resx` and `HomeController.en-UK.resx`. There is some other file name patterns as well. For controllers, I am following this practise. You can do it from Add > New Item and select the Resource file template.

![Add new resource]({{ site.url }}/assets/images/2017/05/add_new_resource.png)

You can create the file name as `ControllerName.languagecode-countrycode.resx`, for this post I am creating resource file in Hindi language.

![Hindi Resource file]({{ site.url }}/assets/images/2017/05/resource_file_for_hindi.png)

You can use the Name key to identify the string and value will your localized string. Next you need to configure ASP.NET Core to load the resources and inject it to the controllers using the in built DI engine. To do this you need to modify Startup class, `ConfigureServices()` and `Configure()` methods.

{% highlight CSharp %}
public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");
    services.AddMvc();
}
{% endhighlight %}

And here is the `Configure` method.

{% highlight CSharp %}
public void Configure(IApplicationBuilder app)
{
    var supportedCultures = new List<CultureInfo>
    {
        new CultureInfo("en-US"),
        new CultureInfo("ml-IN"),
        new CultureInfo("hi-IN")
    };

    var options = new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en-US"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures,
    };

    app.UseRequestLocalization(options);
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}
{% endhighlight %}

In the `ConfigureServices()` method, you are adding the Localization middleware and configuring the location to load the resource files. And in the `Configure()` method, the supported resources are added and enabling the request localization. You can get the instance of `IStringLocalizer<HomeController>` class inside your controller. And you can read the localized strings by providing the key.

{% highlight CSharp %}
public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _stringLocalizer;
    public HomeController(IStringLocalizer<HomeController> stringLocalizer)
    {
        _stringLocalizer = stringLocalizer;
    }
    public IActionResult Index()
    {
        ViewData["Welcome"] = _stringLocalizer["Welcome"];
        return View();
    }
}
{% endhighlight %}

In the view, I am using `@ViewData["Welcome"]` code to display the localized resource string.

You can test using by passing culture as query string, like for Hindi, you should pass `culture=hi-in`.

Here is the screenshot of the app running on my machine.

![Browser rendering on my machine]({{ site.url }}/assets/images/2017/05/browser_rendering_localized_strings.png)

Useful resources

1. [ASP.NET Core documentation on localization](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization)
2. [Localization github repo](https://github.com/aspnet/Localization)

Happy Programming :)


text:
<?php

namespace Spy\Timeline\Spread\Entry;

use Spy\Timeline\Model\ComponentInterface;

class Entry implements EntryInterface
{
    /**
     * @var ComponentInterface
     */
    protected $subject;

    /**
     * @param ComponentInterface $subject subject
     */
    public function __construct(ComponentInterface $subject)
    {
        $this->subject = $subject;
    }

    /**
     * {@inheritdoc}
     */
    public function getIdent()
    {
        return $this->subject->getHash();
    }

    /**
     * {@inheritdoc}
     */
    public function getSubject()
    {
        return $this->subject;
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _link = require('react-toolbox/lib/link');

var _link2 = _interopRequireDefault(_link);

var _asSchemaField = require('./asSchemaField');

var _asSchemaField2 = _interopRequireDefault(_asSchemaField);

var _schemaFormPropTypes = require('./schemaFormPropTypes');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

Function.prototype.$asyncbind = function anonymous(self, catcher) {
  var resolver = this;

  if (catcher === true) {
    if (!Function.prototype.$asyncbind.EagerThenable) Function.prototype.$asyncbind.EagerThenable = function factory(tick) {
      var _tasks = [];

      if (!tick) {
        try {
          tick = process.nextTick;
        } catch (ex) {
          tick = function tick(p) {
            setTimeout(p, 0);
          };
        }
      }

      function _untask() {
        for (var i = 0; i < _tasks.length; i += 2) {
          var t = _tasks[i + 1],
              r = _tasks[i];

          for (var j = 0; j < t.length; j++) {
            t[j].call(null, r);
          }
        }

        _tasks = [];
      }

      function isThenable(obj) {
        return obj && obj instanceof Object && typeof obj.then === 'function';
      }

      function EagerThenable(resolver) {
        function done(inline) {
          var w;
          if (_sync || phase < 0 || (w = _thens[phase]).length === 0) return;

          _tasks.push(result, w);

          _thens = [[], []];
          if (_tasks.length === 2) inline ? _untask() : tick(_untask);
        }

        function resolveThen(x) {
          if (phase >= 0) return;
          if (isThenable(x)) return x.then(resolveThen, rejectThen);
          phase = 0;
          result = x;
          done(true);
        }

        function rejectThen(x) {
          if (phase >= 0) return;
          if (isThenable(x)) return x.then(resolveThen, rejectThen);
          phase = 1;
          result = x;
          done(true);
        }

        function settler(resolver, rejecter) {
          _thens[0].push(resolver);

          _thens[1].push(rejecter);

          done();
        }

        function toString() {
          return 'EagerThenable{' + {
            '-1': 'pending',
            0: 'resolved',
            1: 'rejected'
          }[phase] + '}=' + result.toString();
        }

        function guard() {
          try {
            resolver.call(null, resolveThen, rejectThen);
          } catch (ex) {
            rejectThen(ex);
          }
        }

        this.then = settler;
        this.toString = toString;
        var _thens = [[], []],
            _sync = true,
            phase = -1,
            result;
        guard();
        _sync = false;
        done();
      }

      EagerThenable.resolve = function (v) {
        return isThenable(v) ? v : {
          then: function then(resolve, reject) {
            return resolve(v);
          }
        };
      };

      return EagerThenable;
    }();
    return new Function.prototype.$asyncbind.EagerThenable(boundThen);
  }

  if (catcher) {
    if (Function.prototype.$asyncbind.wrapAsyncStack) catcher = Function.prototype.$asyncbind.wrapAsyncStack(catcher);
    return then;
  }

  function then(result, error) {
    try {
      return result && result instanceof Object && typeof result.then === 'function' ? result.then(then, catcher) : resolver.call(self, result, error || catcher);
    } catch (ex) {
      return (error || catcher)(ex);
    }
  }

  function boundThen(result, error) {
    return resolver.call(self, result, error);
  }

  boundThen.then = boundThen;
  return boundThen;
};

var BoolLink = function (_React$Component) {
  _inherits(BoolLink, _React$Component);

  function BoolLink() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, BoolLink);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = BoolLink.__proto__ || Object.getPrototypeOf(BoolLink)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function () {
      _this.props.onChange(!_this.props.value);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(BoolLink, [{
    key: 'render',
    value: function render() {
      var label = this.props.formField.titleMap[0].name ? this.props.formField.titleMap[0].name : this.props.formField.titleMap[0];

      if (this.props.value) {
        label = this.props.formField.titleMap[1].name ? this.props.formField.titleMap[1].name : this.props.formField.titleMap[1];
      }

      return _react2.default.createElement(
        _link2.default,
        _extends({}, this.props.formField.props, { onClick: this.onClick }),
        label
      );
    }
  }]);

  return BoolLink;
}(_react2.default.Component);

BoolLink.propTypes = {
  formField: _schemaFormPropTypes.formShape,
  value: _propTypes2.default.bool,
  onChange: _propTypes2.default.func
};

exports.default = (0, _asSchemaField2.default)(BoolLink);
module.exports = exports['default'];


text:
/**
* HTML2JS is a Grunt plugin that takes all of your template files and
* places them into JavaScript files as strings that are added to
* AngularJS's template cache. This means that the templates too become
* part of the initial payload as one JavaScript file. Neat!
*/

module.exports = function(grunt) {

	grunt.config.set('html2js', {
		dev: {
			options: {
				base: 'assets/src/app',
				// changing the module name here will be set as the angular module name of for the template cache
				// So in this case, our code will use 'templates-app' as the module name
				module: 'templates-app'
			},
			files: {
				'.tmp/public/templates.js':  require('../pipeline').templateFilesToInject
			}
		}
	});

	grunt.loadNpmTasks('grunt-html2js');
};


text:
package com.intellij.openapi.vcs.configurable;

import com.intellij.ide.actions.ShowFilePathAction;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nls;
import javax.annotation.Nonnull;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;

public class VcsGeneralConfigurationPanel implements SearchableConfigurable {

  private JCheckBox myForceNonEmptyComment;
  private JCheckBox myShowReadOnlyStatusDialog;

  private JRadioButton myShowDialogOnAddingFile;
  private JRadioButton myPerformActionOnAddingFile;
  private JRadioButton myDoNothingOnAddingFile;

  private JRadioButton myShowDialogOnRemovingFile;
  private JRadioButton myPerformActionOnRemovingFile;
  private JRadioButton myDoNothingOnRemovingFile;

  private JPanel myPanel;

  private final JRadioButton[] myOnFileAddingGroup;
  private final JRadioButton[] myOnFileRemovingGroup;

  private final Project myProject;
  private JPanel myPromptsPanel;

  Map<VcsShowOptionsSettingImpl, JCheckBox> myPromptOptions = new LinkedHashMap<VcsShowOptionsSettingImpl, JCheckBox>();
  private JPanel myRemoveConfirmationPanel;
  private JPanel myAddConfirmationPanel;
  private JCheckBox myCbOfferToMoveChanges;
  private JComboBox myFailedCommitChangelistCombo;
  private JComboBox myOnPatchCreation;
  private JCheckBox myClearInitialCommitMessage;
  private ButtonGroup myEmptyChangelistRemovingGroup;

  public VcsGeneralConfigurationPanel(final Project project) {

    myProject = project;

    myOnFileAddingGroup = new JRadioButton[]{
      myShowDialogOnAddingFile,
      myPerformActionOnAddingFile,
      myDoNothingOnAddingFile
    };

    myOnFileRemovingGroup = new JRadioButton[]{
      myShowDialogOnRemovingFile,
      myPerformActionOnRemovingFile,
      myDoNothingOnRemovingFile
    };

    myPromptsPanel.setLayout(new GridLayout(3, 0));

    List<VcsShowOptionsSettingImpl> options = ProjectLevelVcsManagerEx.getInstanceEx(project).getAllOptions();

    for (VcsShowOptionsSettingImpl setting : options) {
      if (!setting.getApplicableVcses().isEmpty() || project.isDefault()) {
        final JCheckBox checkBox = new JCheckBox(setting.getDisplayName());
        myPromptsPanel.add(checkBox);
        myPromptOptions.put(setting, checkBox);
      }
    }

    myPromptsPanel.setSize(myPromptsPanel.getPreferredSize());                           // todo check text!
    myOnPatchCreation.setName((SystemInfo.isMac ? "Reveal patch in" : "Show patch in ") +
                              ShowFilePathAction.getFileManagerName() + " after creation:");
  }

  public void apply() throws ConfigurationException {

    VcsConfiguration settings = VcsConfiguration.getInstance(myProject);

    settings.FORCE_NON_EMPTY_COMMENT = myForceNonEmptyComment.isSelected();
    settings.CLEAR_INITIAL_COMMIT_MESSAGE = myClearInitialCommitMessage.isSelected();
    settings.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT = myCbOfferToMoveChanges.isSelected();
    settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS = getSelected(myEmptyChangelistRemovingGroup);
    settings.MOVE_TO_FAILED_COMMIT_CHANGELIST = getFailedCommitConfirm();

    for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) {
      setting.setValue(myPromptOptions.get(setting).isSelected());
    }

    getAddConfirmation().setValue(getSelected(myOnFileAddingGroup));
    getRemoveConfirmation().setValue(getSelected(myOnFileRemovingGroup));
    applyPatchOption(settings);

    getReadOnlyStatusHandler().getState().SHOW_DIALOG = myShowReadOnlyStatusDialog.isSelected();
  }

  private void applyPatchOption(VcsConfiguration settings) {
    settings.SHOW_PATCH_IN_EXPLORER = getShowPatchValue();
  }

  @javax.annotation.Nullable
  private Boolean getShowPatchValue() {
    final int index = myOnPatchCreation.getSelectedIndex();
    if (index == 0) {
      return null;
    } else if (index == 1) {
      return true;
    } else {
      return false;
    }
  }

  private VcsShowConfirmationOption.Value getFailedCommitConfirm() {
    switch(myFailedCommitChangelistCombo.getSelectedIndex()) {
      case 0: return VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY;
      case 1: return VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY;
      default: return VcsShowConfirmationOption.Value.SHOW_CONFIRMATION;
    }
  }

  private VcsShowConfirmationOption getAddConfirmation() {
    return ProjectLevelVcsManagerEx.getInstanceEx(myProject)
      .getConfirmation(VcsConfiguration.StandardConfirmation.ADD);
  }

  private VcsShowConfirmationOption getRemoveConfirmation() {
    return ProjectLevelVcsManagerEx.getInstanceEx(myProject)
      .getConfirmation(VcsConfiguration.StandardConfirmation.REMOVE);
  }

  private static VcsShowConfirmationOption.Value getSelected(JRadioButton[] group) {
    if (group[0].isSelected()) return VcsShowConfirmationOption.Value.SHOW_CONFIRMATION;
    if (group[1].isSelected()) return VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY;
    return VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY;
  }

  private static VcsShowConfirmationOption.Value getSelected(ButtonGroup group) {
    switch (UIUtil.getSelectedButton(group)) {
      case 0:
        return VcsShowConfirmationOption.Value.SHOW_CONFIRMATION;
      case 1:
        return VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY;
    }
    return VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY;
  }

  private ReadonlyStatusHandlerImpl getReadOnlyStatusHandler() {
    return ((ReadonlyStatusHandlerImpl)ReadonlyStatusHandler.getInstance(myProject));
  }

  public boolean isModified() {

    VcsConfiguration settings = VcsConfiguration.getInstance(myProject);
    if (settings.FORCE_NON_EMPTY_COMMENT != myForceNonEmptyComment.isSelected()){
      return true;
    }
    if (settings.CLEAR_INITIAL_COMMIT_MESSAGE != myClearInitialCommitMessage.isSelected()){
      return true;
    }
    if (settings.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT != myCbOfferToMoveChanges.isSelected()){
      return true;
    }
    if (settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS != getSelected(myEmptyChangelistRemovingGroup)){
      return true;
    }

    if (!Comparing.equal(getFailedCommitConfirm(), settings.MOVE_TO_FAILED_COMMIT_CHANGELIST)) {
      return true;
    }

    if (getReadOnlyStatusHandler().getState().SHOW_DIALOG != myShowReadOnlyStatusDialog.isSelected()) {
      return true;
    }

    for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) {
      if (setting.getValue() != myPromptOptions.get(setting).isSelected()) return true;
    }

    if (getSelected(myOnFileAddingGroup) != getAddConfirmation().getValue()) return true;
    if (getSelected(myOnFileRemovingGroup) != getRemoveConfirmation().getValue()) return true;
    if (! Comparing.equal(settings.SHOW_PATCH_IN_EXPLORER, getShowPatchValue())) return true;

    return false;
  }

  public void reset() {
    VcsConfiguration settings = VcsConfiguration.getInstance(myProject);
    myForceNonEmptyComment.setSelected(settings.FORCE_NON_EMPTY_COMMENT);
    myClearInitialCommitMessage.setSelected(settings.CLEAR_INITIAL_COMMIT_MESSAGE);
    myCbOfferToMoveChanges.setSelected(settings.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT);
    int id = settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS.getId();
    UIUtil.setSelectedButton(myEmptyChangelistRemovingGroup, id == 0 ? 0 : id == 1 ? 2 : 1);
    myShowReadOnlyStatusDialog.setSelected(getReadOnlyStatusHandler().getState().SHOW_DIALOG);
    if (settings.MOVE_TO_FAILED_COMMIT_CHANGELIST == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) {
      myFailedCommitChangelistCombo.setSelectedIndex(0);
    }
    else if (settings.MOVE_TO_FAILED_COMMIT_CHANGELIST == VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) {
      myFailedCommitChangelistCombo.setSelectedIndex(1);
    }
    else {
      myFailedCommitChangelistCombo.setSelectedIndex(2);
    }

    for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) {
      myPromptOptions.get(setting).setSelected(setting.getValue());
    }

    selectInGroup(myOnFileAddingGroup, getAddConfirmation());
    selectInGroup(myOnFileRemovingGroup, getRemoveConfirmation());
    if (settings.SHOW_PATCH_IN_EXPLORER == null) {
      myOnPatchCreation.setSelectedIndex(0);
    } else if (Boolean.TRUE.equals(settings.SHOW_PATCH_IN_EXPLORER)) {
      myOnPatchCreation.setSelectedIndex(1);
    } else {
      myOnPatchCreation.setSelectedIndex(2);
    }
  }

  private static void selectInGroup(final JRadioButton[] group, final VcsShowConfirmationOption confirmation) {
    final VcsShowConfirmationOption.Value value = confirmation.getValue();
    final int index;
    //noinspection EnumSwitchStatementWhichMissesCases
    switch(value) {
      case SHOW_CONFIRMATION: index = 0; break;
      case DO_ACTION_SILENTLY: index = 1; break;
      default: index = 2;
    }
    group[index].setSelected(true);
  }

  public JComponent getPanel() {
    return myPanel;
  }

  public void updateAvailableOptions(final Collection<AbstractVcs> activeVcses) {
    for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) {
      final JCheckBox checkBox = myPromptOptions.get(setting);
      checkBox.setEnabled(setting.isApplicableTo(activeVcses) || myProject.isDefault());
      if (!myProject.isDefault()) {
        checkBox.setToolTipText(VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(setting.getApplicableVcses())));
      }
    }

    if (!myProject.isDefault()) {
      final ProjectLevelVcsManagerEx vcsManager = ProjectLevelVcsManagerEx.getInstanceEx(myProject);
      final VcsShowConfirmationOptionImpl addConfirmation = vcsManager.getConfirmation(VcsConfiguration.StandardConfirmation.ADD);
      UIUtil.setEnabled(myAddConfirmationPanel, addConfirmation.isApplicableTo(activeVcses), true);
      myAddConfirmationPanel.setToolTipText(
        VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(addConfirmation.getApplicableVcses())));

      final VcsShowConfirmationOptionImpl removeConfirmation = vcsManager.getConfirmation(VcsConfiguration.StandardConfirmation.REMOVE);
      UIUtil.setEnabled(myRemoveConfirmationPanel, removeConfirmation.isApplicableTo(activeVcses), true);
      myRemoveConfirmationPanel.setToolTipText(
        VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(removeConfirmation.getApplicableVcses())));
    }
  }

  private static String composeText(final List<AbstractVcs> applicableVcses) {
    final TreeSet<String> result = new TreeSet<String>();
    for (AbstractVcs abstractVcs : applicableVcses) {
      result.add(abstractVcs.getDisplayName());
    }
    return StringUtil.join(result, ", ");
  }

  @Nls
  public String getDisplayName() {
    return "Confirmation";
  }

  public JComponent createComponent() {
    return getPanel();
  }

  public void disposeUIResources() {
  }

  @Nonnull
  public String getId() {
    return "project.propVCSSupport.Confirmation";
  }

  public Runnable enableSearch(String option) {
    return null;
  }
}


text:
using AutoMapper;
using NewsletterSender.WebApplication.Models;
using NewsletterSender.WebApplication.Services;

namespace NewsletterSender.WebApplication.Configuration.Mapper.Converters
{
    public class LinkToEmailLinkDataConverter : ITypeConverter<Link, EmailLinkData>
    {
        public EmailLinkData Convert(Link source, EmailLinkData destination, ResolutionContext context)
        {
            destination = new EmailLinkData();
            destination.Title = source.Title;
            destination.Url = source.Url;
            destination.LinkCategoryName = source.LinkCategory.Name;
            return destination;
        }
    }
}


text:
namespace sandbox {

namespace {

DWORD GetObjectSecurityDescriptor(HANDLE handle,
                                  SECURITY_INFORMATION security_info,
                                  std::vector<char>* security_desc_buffer,
                                  PSECURITY_DESCRIPTOR* security_desc) {
  DWORD last_error = 0;
  DWORD length_needed = 0;

  ::GetKernelObjectSecurity(handle, security_info, nullptr, 0, &length_needed);
  last_error = ::GetLastError();
  if (last_error != ERROR_INSUFFICIENT_BUFFER)
    return last_error;

  security_desc_buffer->resize(length_needed);
  *security_desc =
      reinterpret_cast<PSECURITY_DESCRIPTOR>(security_desc_buffer->data());

  if (!::GetKernelObjectSecurity(handle, security_info, *security_desc,
                                 length_needed, &length_needed)) {
    return ::GetLastError();
  }

  return ERROR_SUCCESS;
}

}  // namespace

DWORD CreateRestrictedToken(HANDLE effective_token,
                            TokenLevel security_level,
                            IntegrityLevel integrity_level,
                            TokenType token_type,
                            bool lockdown_default_dacl,
                            PSID unique_restricted_sid,
                            base::win::ScopedHandle* token) {
  RestrictedToken restricted_token;
  restricted_token.Init(effective_token);
  if (lockdown_default_dacl)
    restricted_token.SetLockdownDefaultDacl();
  if (unique_restricted_sid) {
    restricted_token.AddDefaultDaclSid(Sid(unique_restricted_sid), GRANT_ACCESS,
                                       GENERIC_ALL);
    restricted_token.AddDefaultDaclSid(Sid(WinCreatorOwnerRightsSid),
                                       GRANT_ACCESS, READ_CONTROL);
  }

  std::vector<std::wstring> privilege_exceptions;
  std::vector<Sid> sid_exceptions;

  bool deny_sids = true;
  bool remove_privileges = true;

  switch (security_level) {
    case USER_UNPROTECTED: {
      deny_sids = false;
      remove_privileges = false;
      break;
    }
    case USER_RESTRICTED_SAME_ACCESS: {
      deny_sids = false;
      remove_privileges = false;

      unsigned err_code = restricted_token.AddRestrictingSidAllSids();
      if (ERROR_SUCCESS != err_code)
        return err_code;

      break;
    }
    case USER_NON_ADMIN: {
      sid_exceptions.push_back(WinBuiltinUsersSid);
      sid_exceptions.push_back(WinWorldSid);
      sid_exceptions.push_back(WinInteractiveSid);
      sid_exceptions.push_back(WinAuthenticatedUserSid);
      privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
      break;
    }
    case USER_RESTRICTED_NON_ADMIN: {
      sid_exceptions.push_back(WinBuiltinUsersSid);
      sid_exceptions.push_back(WinWorldSid);
      sid_exceptions.push_back(WinInteractiveSid);
      sid_exceptions.push_back(WinAuthenticatedUserSid);
      privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
      restricted_token.AddRestrictingSid(WinBuiltinUsersSid);
      restricted_token.AddRestrictingSid(WinWorldSid);
      restricted_token.AddRestrictingSid(WinInteractiveSid);
      restricted_token.AddRestrictingSid(WinAuthenticatedUserSid);
      restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
      restricted_token.AddRestrictingSidCurrentUser();
      restricted_token.AddRestrictingSidLogonSession();
      if (unique_restricted_sid)
        restricted_token.AddRestrictingSid(Sid(unique_restricted_sid));
      break;
    }
    case USER_INTERACTIVE: {
      sid_exceptions.push_back(WinBuiltinUsersSid);
      sid_exceptions.push_back(WinWorldSid);
      sid_exceptions.push_back(WinInteractiveSid);
      sid_exceptions.push_back(WinAuthenticatedUserSid);
      privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
      restricted_token.AddRestrictingSid(WinBuiltinUsersSid);
      restricted_token.AddRestrictingSid(WinWorldSid);
      restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
      restricted_token.AddRestrictingSidCurrentUser();
      restricted_token.AddRestrictingSidLogonSession();
      if (unique_restricted_sid)
        restricted_token.AddRestrictingSid(Sid(unique_restricted_sid));
      break;
    }
    case USER_LIMITED: {
      sid_exceptions.push_back(WinBuiltinUsersSid);
      sid_exceptions.push_back(WinWorldSid);
      sid_exceptions.push_back(WinInteractiveSid);
      privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
      restricted_token.AddRestrictingSid(WinBuiltinUsersSid);
      restricted_token.AddRestrictingSid(WinWorldSid);
      restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
      if (unique_restricted_sid)
        restricted_token.AddRestrictingSid(Sid(unique_restricted_sid));

      // This token has to be able to create objects in BNO.
      // Unfortunately, on Vista+, it needs the current logon sid
      // in the token to achieve this. You should also set the process to be
      // low integrity level so it can't access object created by other
      // processes.
      restricted_token.AddRestrictingSidLogonSession();
      break;
    }
    case USER_RESTRICTED: {
      privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
      restricted_token.AddUserSidForDenyOnly();
      restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
      if (unique_restricted_sid)
        restricted_token.AddRestrictingSid(Sid(unique_restricted_sid));
      break;
    }
    case USER_LOCKDOWN: {
      restricted_token.AddUserSidForDenyOnly();
      restricted_token.AddRestrictingSid(WinNullSid);
      if (unique_restricted_sid)
        restricted_token.AddRestrictingSid(Sid(unique_restricted_sid));
      break;
    }
    default: { return ERROR_BAD_ARGUMENTS; }
  }

  DWORD err_code = ERROR_SUCCESS;
  if (deny_sids) {
    err_code = restricted_token.AddAllSidsForDenyOnly(&sid_exceptions);
    if (ERROR_SUCCESS != err_code)
      return err_code;
  }

  if (remove_privileges) {
    err_code = restricted_token.DeleteAllPrivileges(&privilege_exceptions);
    if (ERROR_SUCCESS != err_code)
      return err_code;
  }

  restricted_token.SetIntegrityLevel(integrity_level);

  switch (token_type) {
    case PRIMARY: {
      err_code = restricted_token.GetRestrictedToken(token);
      break;
    }
    case IMPERSONATION: {
      err_code = restricted_token.GetRestrictedTokenForImpersonation(token);
      break;
    }
    default: {
      err_code = ERROR_BAD_ARGUMENTS;
      break;
    }
  }

  return err_code;
}

DWORD SetObjectIntegrityLabel(HANDLE handle,
                              SE_OBJECT_TYPE type,
                              const wchar_t* ace_access,
                              const wchar_t* integrity_level_sid) {
  // Build the SDDL string for the label.
  std::wstring sddl = L"S:(";    // SDDL for a SACL.
  sddl += SDDL_MANDATORY_LABEL;  // Ace Type is "Mandatory Label".
  sddl += L";;";                 // No Ace Flags.
  sddl += ace_access;            // Add the ACE access.
  sddl += L";;;";                // No ObjectType and Inherited Object Type.
  sddl += integrity_level_sid;   // Trustee Sid.
  sddl += L")";

  DWORD error = ERROR_SUCCESS;
  PSECURITY_DESCRIPTOR sec_desc = nullptr;

  PACL sacl = nullptr;
  BOOL sacl_present = false;
  BOOL sacl_defaulted = false;

  if (::ConvertStringSecurityDescriptorToSecurityDescriptorW(
          sddl.c_str(), SDDL_REVISION, &sec_desc, nullptr)) {
    if (::GetSecurityDescriptorSacl(sec_desc, &sacl_present, &sacl,
                                    &sacl_defaulted)) {
      error = ::SetSecurityInfo(handle, type, LABEL_SECURITY_INFORMATION,
                                nullptr, nullptr, nullptr, sacl);
    } else {
      error = ::GetLastError();
    }

    ::LocalFree(sec_desc);
  } else {
    return ::GetLastError();
  }

  return error;
}

const wchar_t* GetIntegrityLevelString(IntegrityLevel integrity_level) {
  switch (integrity_level) {
    case INTEGRITY_LEVEL_SYSTEM:
      return L"S-1-16-16384";
    case INTEGRITY_LEVEL_HIGH:
      return L"S-1-16-12288";
    case INTEGRITY_LEVEL_MEDIUM:
      return L"S-1-16-8192";
    case INTEGRITY_LEVEL_MEDIUM_LOW:
      return L"S-1-16-6144";
    case INTEGRITY_LEVEL_LOW:
      return L"S-1-16-4096";
    case INTEGRITY_LEVEL_BELOW_LOW:
      return L"S-1-16-2048";
    case INTEGRITY_LEVEL_UNTRUSTED:
      return L"S-1-16-0";
    case INTEGRITY_LEVEL_LAST:
      return nullptr;
  }

  NOTREACHED();
  return nullptr;
}
DWORD SetTokenIntegrityLevel(HANDLE token, IntegrityLevel integrity_level) {
  const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level);
  if (!integrity_level_str) {
    // No mandatory level specified, we don't change it.
    return ERROR_SUCCESS;
  }

  PSID integrity_sid = nullptr;
  if (!::ConvertStringSidToSid(integrity_level_str, &integrity_sid))
    return ::GetLastError();

  TOKEN_MANDATORY_LABEL label = {};
  label.Label.Attributes = SE_GROUP_INTEGRITY;
  label.Label.Sid = integrity_sid;

  DWORD size = sizeof(TOKEN_MANDATORY_LABEL) + ::GetLengthSid(integrity_sid);
  bool result = ::SetTokenInformation(token, TokenIntegrityLevel, &label, size);
  auto last_error = ::GetLastError();
  ::LocalFree(integrity_sid);

  return result ? ERROR_SUCCESS : last_error;
}

DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
  // We don't check for an invalid level here because we'll just let it
  // fail on the SetTokenIntegrityLevel call later on.
  if (integrity_level == INTEGRITY_LEVEL_LAST) {
    // No mandatory level specified, we don't change it.
    return ERROR_SUCCESS;
  }

  HANDLE token_handle;
  if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
                          &token_handle))
    return ::GetLastError();

  base::win::ScopedHandle token(token_handle);

  return SetTokenIntegrityLevel(token.Get(), integrity_level);
}

DWORD HardenTokenIntegrityLevelPolicy(HANDLE token) {
  std::vector<char> security_desc_buffer;
  PSECURITY_DESCRIPTOR security_desc = nullptr;
  DWORD last_error = GetObjectSecurityDescriptor(
      token, LABEL_SECURITY_INFORMATION, &security_desc_buffer, &security_desc);
  if (last_error != ERROR_SUCCESS)
    return last_error;

  PACL sacl = nullptr;
  BOOL sacl_present = false;
  BOOL sacl_defaulted = false;

  if (!::GetSecurityDescriptorSacl(security_desc, &sacl_present, &sacl,
                                   &sacl_defaulted)) {
    return ::GetLastError();
  }

  for (DWORD ace_index = 0; ace_index < sacl->AceCount; ++ace_index) {
    PSYSTEM_MANDATORY_LABEL_ACE ace;

    if (::GetAce(sacl, ace_index, reinterpret_cast<LPVOID*>(&ace)) &&
        ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) {
      ace->Mask |= SYSTEM_MANDATORY_LABEL_NO_READ_UP |
                   SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP;
      break;
    }
  }

  if (!::SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION,
                                 security_desc))
    return ::GetLastError();

  return ERROR_SUCCESS;
}

DWORD HardenProcessIntegrityLevelPolicy() {
  HANDLE token_handle;
  if (!::OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER,
                          &token_handle))
    return ::GetLastError();

  base::win::ScopedHandle token(token_handle);

  return HardenTokenIntegrityLevelPolicy(token.Get());
}

DWORD CreateLowBoxToken(HANDLE base_token,
                        TokenType token_type,
                        PSECURITY_CAPABILITIES security_capabilities,
                        PHANDLE saved_handles,
                        DWORD saved_handles_count,
                        base::win::ScopedHandle* token) {
  NtCreateLowBoxToken CreateLowBoxToken = nullptr;
  ResolveNTFunctionPtr("NtCreateLowBoxToken", &CreateLowBoxToken);

  if (base::win::GetVersion() < base::win::Version::WIN8)
    return ERROR_CALL_NOT_IMPLEMENTED;

  if (token_type != PRIMARY && token_type != IMPERSONATION)
    return ERROR_INVALID_PARAMETER;

  if (!token)
    return ERROR_INVALID_PARAMETER;

  base::win::ScopedHandle base_token_handle;
  if (!base_token) {
    HANDLE process_token = nullptr;
    if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
                            &process_token)) {
      return ::GetLastError();
    }
    base_token_handle.Set(process_token);
    base_token = process_token;
  }
  OBJECT_ATTRIBUTES obj_attr;
  InitializeObjectAttributes(&obj_attr, nullptr, 0, nullptr, nullptr);
  HANDLE token_lowbox = nullptr;

  NTSTATUS status = CreateLowBoxToken(
      &token_lowbox, base_token, TOKEN_ALL_ACCESS, &obj_attr,
      security_capabilities->AppContainerSid,
      security_capabilities->CapabilityCount,
      security_capabilities->Capabilities, saved_handles_count,
      saved_handles_count > 0 ? saved_handles : nullptr);
  if (!NT_SUCCESS(status))
    return GetLastErrorFromNtStatus(status);

  base::win::ScopedHandle token_lowbox_handle(token_lowbox);
  DCHECK(token_lowbox_handle.IsValid());

  // Default from NtCreateLowBoxToken is a Primary token.
  if (token_type == PRIMARY) {
    *token = std::move(token_lowbox_handle);
    return ERROR_SUCCESS;
  }

  HANDLE dup_handle = nullptr;
  if (!::DuplicateTokenEx(token_lowbox_handle.Get(), TOKEN_ALL_ACCESS, nullptr,
                          ::SecurityImpersonation, ::TokenImpersonation,
                          &dup_handle)) {
    return ::GetLastError();
  }

  // Copy security descriptor from primary token as the new object will have
  // the DACL from the current token's default DACL.
  base::win::ScopedHandle token_for_sd(dup_handle);
  std::vector<char> security_desc_buffer;
  PSECURITY_DESCRIPTOR security_desc = nullptr;
  DWORD last_error = GetObjectSecurityDescriptor(
      token_lowbox_handle.Get(), DACL_SECURITY_INFORMATION,
      &security_desc_buffer, &security_desc);
  if (last_error != ERROR_SUCCESS)
    return last_error;

  if (!::SetKernelObjectSecurity(token_for_sd.Get(), DACL_SECURITY_INFORMATION,
                                 security_desc)) {
    return ::GetLastError();
  }

  *token = std::move(token_for_sd);

  return ERROR_SUCCESS;
}

DWORD CreateLowBoxObjectDirectory(PSID lowbox_sid,
                                  bool open_directory,
                                  base::win::ScopedHandle* directory) {
  DWORD session_id = 0;
  if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &session_id))
    return ::GetLastError();

  LPWSTR sid_string = nullptr;
  if (!::ConvertSidToStringSid(lowbox_sid, &sid_string))
    return ::GetLastError();

  std::unique_ptr<wchar_t, LocalFreeDeleter> sid_string_ptr(sid_string);
  std::wstring directory_path = base::StringPrintf(
      L"\\Sessions\\%d\\AppContainerNamedObjects\\%ls", session_id, sid_string);

  NtCreateDirectoryObjectFunction CreateObjectDirectory = nullptr;
  ResolveNTFunctionPtr("NtCreateDirectoryObject", &CreateObjectDirectory);

  OBJECT_ATTRIBUTES obj_attr;
  UNICODE_STRING obj_name;
  DWORD attributes = OBJ_CASE_INSENSITIVE;
  if (open_directory)
    attributes |= OBJ_OPENIF;

  sandbox::InitObjectAttribs(directory_path, attributes, nullptr, &obj_attr,
                             &obj_name, nullptr);

  HANDLE handle = nullptr;
  NTSTATUS status =
      CreateObjectDirectory(&handle, DIRECTORY_ALL_ACCESS, &obj_attr);

  if (!NT_SUCCESS(status))
    return GetLastErrorFromNtStatus(status);
  directory->Set(handle);

  return ERROR_SUCCESS;
}

}  // namespace sandbox


text:
<?php

namespace Symfony\Bridge\RulerZ\Form;

use Symfony\Component\Form\DataTransformerInterface;

class SpecificationToBooleanTransformer implements DataTransformerInterface
{
    /**
     * @var string
     */
    private $specificationClass;

    /**
     * @var array
     */
    private $constructorArgs;

    public function __construct($specificationClass, array $constructorArgs = [])
    {
        $this->specificationClass = $specificationClass;
        $this->constructorArgs = $constructorArgs;
    }

    /**
     * Transforms a specification into a boolean.
     *
     * @param \RulerZ\Spec\Specification|null $specification
     *
     * @return bool
     */
    public function transform($specification)
    {
        if ($specification === null) {
            return false;
        }

        return (bool) ((string) $specification);
    }

    /**
     * Transforms a value into a specification.
     *
     * @param bool $boolean
     *
     * @return \RulerZ\Spec\Specification|null
     */
    public function reverseTransform($boolean)
    {
        if (!$boolean) {
            return null;
        }

        $rClass = new \ReflectionClass($this->specificationClass);

        if ($rClass->getConstructor() && $rClass->getConstructor()->getNumberOfParameters() > 0) {
            return $rClass->newInstanceArgs($this->constructorArgs);
        }

        return $rClass->newInstance();
    }
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.WebApps.Models;
using Microsoft.Azure.Commands.WebApps.Utilities;
using Microsoft.Azure.Management.WebSites.Models;
using System.Collections.Generic;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.WebApps.Cmdlets.DeploymentSlots
{
    /// <summary>
    /// this commandlet will let you get a new Azure Web app slot using ARM APIs
    /// </summary>
    [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "WebAppSlot")]
    [OutputType(typeof(PSSite))]
    public class GetAzureWebAppSlotCmdlet : WebAppBaseClientCmdLet
    {
        protected const string ParameterSet1Name = "S1";
        protected const string ParameterSet2Name = "S2";

        [Parameter(ParameterSetName = ParameterSet1Name, Position = 0, Mandatory = true, HelpMessage = "The name of the resource group.")]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(ParameterSetName = ParameterSet1Name, Position = 1, Mandatory = true, HelpMessage = "The name of the web app.", ValueFromPipelineByPropertyName = true)]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }

        [Parameter(Position = 2, Mandatory = false, HelpMessage = "The name of the web app slot.")]
        [ValidateNotNullOrEmpty]
        public string Slot { get; set; }

        [Parameter(ParameterSetName = ParameterSet2Name, Position = 0, Mandatory = true, HelpMessage = "The web app object", ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        public PSSite WebApp { get; set; }

        public override void ExecuteCmdlet()
        {
            if (string.Equals(ParameterSetName, ParameterSet2Name))
            {
                string rg, name, slot;

                if (!CmdletHelpers.TryParseWebAppMetadataFromResourceId(WebApp.Id, out rg, out name, out slot, true))
                {
                    throw new ValidationMetadataException("Input object is a deployment slot but should be a production web app");
                }

                ResourceGroupName = rg;
                Name = name;
            }

            if (string.IsNullOrWhiteSpace(Slot))
            {
                var output = WebsitesClient.ListWebApps(ResourceGroupName, Name);
                var slots = new List<PSSite>();
                foreach(var slot in output)
                {
                    slots.Add(new PSSite(slot));
                }
                WriteObject(slots, true);
            }
            else
            {
                WriteObject(new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, Name, Slot)));
            }
        }
    }
}


text:
<?php

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserCenterPolicy
{
    use HandlesAuthorization;

    public function self(User $user, User $u)
    {
        return $user->id === $u->id or $user->isAdmin();
    }

}


text:
<?php
namespace HodgePodge\Cache;

use HodgePodge\Interfaces;

class CacheLite extends \Cache_Lite implements Interfaces\Cache
{
    private $cache_group = 'default';
    private $cache_id = null;

    public function __construct($id, $group = null)
    {
        global $config;
        $this->cache_id = $id;
        if($group) $this->cache_group = $group;

        $options = array(
            'lifeTime' => \HodgePodge\Core\Cache::$lifetime[$group ?: 'default'] ?: 3600,
            'pearErrorMode' => CACHE_LITE_ERROR_DIE, // Removes reliance on PEAR_Error class (Though obviously not as good!)
            'cacheDir' => ($config['cache_dir']?:$config['cache']['dir']),
            'automaticSerialization' => true,
        );
        parent::__construct($options);
    }

    public function get()
    {
        global $config;
        if ($config['cache']['disable']) return false;

        return parent::get($this->cache_id, $this->cache_group);
    }

    public function save($contents)
    {
        global $config;
        if ($config['cache']['disable']) return false;

        return parent::save($contents, $this->cache_id, $this->cache_group);
    }

    public function delete()
    {
        global $config;
        if ($config['cache']['disable']) return false;

        return parent::remove($this->cache_id, $this->cache_group);
    }

}


text:
package com.weather.forecast.exceptions;

public class GoogleAPIException extends Exception {

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 45L;

	public GoogleAPIException(String exception) {
		super(exception);
	}
}


text:
PROJECT=gitlab
RELEASE_BUCKET=downloads-packages
RELEASE_BUCKET_REGION=eu-west-1
SECRET_DIR:=$(shell openssl rand -hex 20)
PLATFORM_DIR:=$(shell bundle exec support/ohai-helper platform-dir)
PACKAGECLOUD_USER=gitlab
PACKAGECLOUD_REPO:=$(shell support/repo_name.sh)
PACKAGECLOUD_OS:=$(shell bundle exec support/ohai-helper repo-string)

build:
	bin/omnibus build ${PROJECT} --override append_timestamp:false --log-level info

# No need to suppress timestamps on the test builds
test_build:
	bin/omnibus build ${PROJECT} --log-level info

# If this task were called 'release', running 'make release' would confuse Make
# because there exists a file called 'release.sh' in this directory. Make has
# built-in rules on how to build .sh files. By calling this task do_release, it
# can coexist with the release.sh file.
do_release: no_changes on_tag purge build move_to_platform_dir sync packagecloud

# Redefine RELEASE_BUCKET for test builds
test: RELEASE_BUCKET=omnibus-builds
test: no_changes purge test_build move_to_platform_dir sync

# Redefine PLATFORM_DIR for Raspberry Pi 2 packages.
do_rpi2_release: PLATFORM_DIR=raspberry-pi2
do_rpi2_release: PACKAGECLOUD_REPO=raspberry-pi2
do_rpi2_release: no_changes purge test_build move_to_platform_dir sync packagecloud

no_changes:
	git diff --quiet HEAD

on_tag:
	git describe --exact-match

purge:
	# Force a new clone of gitlab-rails because we change remotes for CE/EE
	rm -rf /var/cache/omnibus/src/gitlab-rails
	# Force a new download of Curl's certificate bundle because it gets updated
	# upstream silently once every while
	rm -rf /var/cache/omnibus/cache/cacert.pem
	# Clear out old packages to prevent uploading them a second time to S3
	rm -rf /var/cache/omnibus/pkg
	mkdir -p pkg
	(cd pkg && find . -delete)

# Instead of pkg/gitlab-xxx.deb, put all files in pkg/ubuntu/gitlab-xxx.deb
move_to_platform_dir:
	mv pkg ${PLATFORM_DIR}
	mkdir pkg
	mv ${PLATFORM_DIR} pkg/

sync: move_to_secret_dir md5 s3_sync

move_to_secret_dir:
	if support/is_gitlab_ee.sh ; then \
	  mv pkg ${SECRET_DIR} \
	  && mkdir pkg \
	  && mv ${SECRET_DIR} pkg/ \
	  ; fi

md5:
	find pkg -name '*.json' -exec cat {} \;

s3_sync:
	aws s3 sync pkg/ s3://${RELEASE_BUCKET} --acl public-read --region ${RELEASE_BUCKET_REGION}
	# empty line for aws status crud
	# Download URLS:
	find pkg -type f | sed "s|pkg|https://${RELEASE_BUCKET}.s3.amazonaws.com|"

packagecloud:
	# - We set LC_ALL below because package_cloud is picky about the locale
	LC_ALL='en_US.UTF-8' bin/package_cloud push ${PACKAGECLOUD_USER}/${PACKAGECLOUD_REPO}/${PACKAGECLOUD_OS} $(shell find pkg -name '*.rpm' -or -name '*.deb')


text:
#include "tensorflow/lite/delegates/gpu/common/tasks/conv_constants_test_util.h"

#include <vector>

#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/task/testing_util.h"
#include "tensorflow/lite/delegates/gpu/common/tasks/conv_constants.h"

namespace tflite {
namespace gpu {

absl::Status ConvConstantsSimpleWeightsTest(TestExecutionEnvironment* env) {
  TensorFloat32 src_tensor;
  src_tensor.shape = BHWC(1, 2, 2, 2);
  src_tensor.data = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f};

  Convolution2DAttributes attr;
  attr.padding.prepended = HW(0, 0);
  attr.padding.appended = HW(1, 1);
  attr.strides = HW(1, 1);
  attr.dilations = HW(1, 1);
  attr.weights.shape = OHWI(1, 2, 2, 2);
  attr.weights.data = {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f};
  attr.bias.shape = Linear(1);
  attr.bias.data = {0.0f};

  for (auto precision : env->GetSupportedPrecisions()) {
    auto data_type = DeduceDataTypeFromPrecision(precision);
    for (auto storage : env->GetSupportedStorages(data_type)) {
      const float eps = precision == CalculationsPrecision::F32 ? 1e-6f : 1e-3f;
      OperationDef op_def;
      op_def.precision = precision;
      op_def.src_tensors.push_back({data_type, storage, Layout::HWC});
      op_def.dst_tensors.push_back({data_type, storage, Layout::HWC});
      TensorFloat32 dst_tensor;
      GPUOperation operation =
          CreateConvConstants(env->GetGpuInfo(), op_def, attr);
      RETURN_IF_ERROR(env->ExecuteGPUOperation(
          src_tensor, absl::make_unique<GPUOperation>(std::move(operation)),
          BHWC(1, 2, 2, 1), &dst_tensor));
      RETURN_IF_ERROR(
          PointWiseNear({28.0f, 18.0f, 22.0f, 13.0f}, dst_tensor.data, eps));
    }
  }
  return absl::OkStatus();
}

absl::Status ConvConstantsTest(TestExecutionEnvironment* env) {
  TensorFloat32 src_tensor;
  src_tensor.shape = BHWC(1, 2, 2, 2);
  src_tensor.data = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f};

  Convolution2DAttributes attr;
  attr.padding.prepended = HW(0, 0);
  attr.padding.appended = HW(1, 1);
  attr.strides = HW(1, 1);
  attr.dilations = HW(1, 1);
  attr.weights.shape = OHWI(2, 2, 2, 2);
  attr.weights.data = {1.0f, 2.0f,  3.0f,  4.0f,  5.0f,  6.0f,  7.0f,  8.0f,
                       9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f};
  attr.bias.shape = Linear(2);
  attr.bias.data = {0.5f, -0.5f};

  for (auto precision : env->GetSupportedPrecisions()) {
    auto data_type = DeduceDataTypeFromPrecision(precision);
    for (auto storage : env->GetSupportedStorages(data_type)) {
      const float eps = precision == CalculationsPrecision::F32 ? 1e-6f : 1e-3f;
      OperationDef op_def;
      op_def.precision = precision;
      op_def.src_tensors.push_back({data_type, storage, Layout::HWC});
      op_def.dst_tensors.push_back({data_type, storage, Layout::HWC});
      TensorFloat32 dst_tensor;
      GPUOperation operation =
          CreateConvConstants(env->GetGpuInfo(), op_def, attr);
      RETURN_IF_ERROR(env->ExecuteGPUOperation(
          src_tensor, absl::make_unique<GPUOperation>(std::move(operation)),
          BHWC(1, 2, 2, 2), &dst_tensor));
      RETURN_IF_ERROR(PointWiseNear(
          {168.5f, 391.5f, 80.5f, 223.5f, 60.5f, 235.5f, 20.5f, 123.5f},
          dst_tensor.data, eps));
    }
  }
  return absl::OkStatus();
}

}  // namespace gpu
}  // namespace tflite


text:
<component name="libraryTable">
  <library name="postgresql">
    <CLASSES>
      <root url="file://D:/libs/postgresql" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
    <jarDirectory url="file://D:/libs/postgresql" recursive="false" />
  </library>
</component>