text:
namespace base {

class SingleThreadTaskRunner;

namespace trace_event {

// A delegate to isolate CPU frequency monitor functionality mainly for testing.
class BASE_EXPORT CPUFreqMonitorDelegate {
 public:
  CPUFreqMonitorDelegate();

  CPUFreqMonitorDelegate(const CPUFreqMonitorDelegate&) = delete;
  CPUFreqMonitorDelegate& operator=(const CPUFreqMonitorDelegate&) = delete;

  virtual ~CPUFreqMonitorDelegate() = default;

  // Returns a vector of the minimal set of CPU IDs that we need to monitor to
  // get CPU frequency information. For CPUs that operate cores in a cluster,
  // i.e. modern Qualcomm 8 cores, this is CPU0 and CPU4.
  virtual void GetCPUIds(std::vector<unsigned int>* ids) const;

  // Reads the kernel_max_cpu file to determine the max CPU ID, i.e. 7 on an
  // 8-core CPU.
  virtual unsigned int GetKernelMaxCPUs() const;

  // Reads the frequency from the CPUs being monitored and records them.
  virtual void RecordFrequency(unsigned int cpu_id, unsigned int freq);

  // Returns whether or not the tracing category our CPU Frequency counters are
  // in is enabled to determine if we should record.
  virtual bool IsTraceCategoryEnabled() const;

  // Gets the path to CPU frequency related files for a particular CPU ID.
  virtual std::string GetScalingCurFreqPathString(unsigned int cpu_id) const;
  virtual std::string GetRelatedCPUsPathString(unsigned int cpu_id) const;

  // Allows us to delay creating a task runner, necessary because many tests
  // don't like us creating one outside of a TaskEnvironment.
  virtual scoped_refptr<SingleThreadTaskRunner> CreateTaskRunner();
};

// A class for monitoring the CPU frequency on unique cores/clusters.
class BASE_EXPORT CPUFreqMonitor : public TraceLog::EnabledStateObserver {
 public:
  // Overhead of reading one cluster on a Nexus 6P is ~0.1ms per CPU. 50ms seems
  // frequent enough to get a general idea of CPU frequency trends.
  static const size_t kDefaultCPUFreqSampleIntervalMs = 50;

  CPUFreqMonitor();

  CPUFreqMonitor(const CPUFreqMonitor&) = delete;
  CPUFreqMonitor& operator=(const CPUFreqMonitor&) = delete;

  ~CPUFreqMonitor() override;

  static CPUFreqMonitor* GetInstance();

  void Start();
  void Stop();

  // TraceLog::EnabledStateObserver.
  void OnTraceLogEnabled() override;
  void OnTraceLogDisabled() override;

  bool IsEnabledForTesting();

 private:
  friend class CPUFreqMonitorTest;

  CPUFreqMonitor(std::unique_ptr<CPUFreqMonitorDelegate> delegate);

  void Sample(std::vector<std::pair<unsigned int, base::ScopedFD>> fds);

  // Uses the delegate's CreateTaskRunner function to lazily create a task
  // runner so we don't illegally create a task runner on Chrome startup for
  // various tests.
  const scoped_refptr<SingleThreadTaskRunner>& GetOrCreateTaskRunner();

  std::atomic<bool> is_enabled_{false};
  scoped_refptr<SingleThreadTaskRunner> task_runner_;
  std::unique_ptr<CPUFreqMonitorDelegate> delegate_;
  base::WeakPtrFactory<CPUFreqMonitor> weak_ptr_factory_{this};
};

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_CPUFREQ_MONITOR_ANDROID_H_


text:
module VhdlDoctest
  class TestRunner
    def initialize(out, dut_path, test_file, dependencies = [])
      @out = out
      @dut_path = File.expand_path(dut_path)
      @test_file = test_file
      @dependencies = dependencies

      require 'tmpdir'
      @dir = Dir.mktmpdir
    end

    def run
      create_files
      run_test
      report_result
    end

    def create_files
      @test_file.create(@dir)
      create_runner_script
    end

    def dependencies
      dut_dir = File.dirname(@dut_path)
      @dependencies.map { |path| File.expand_path(path, dut_dir) }
    end

    def create_runner_script
      @sh = File.join(@dir, "run.sh")
      File.open(@sh, 'w') do |f|
        f << "#!/bin/sh -e\n\n"
        f << "cd #{@dir}\n"
        f << "ghdl -a --ieee=synopsys -fexplicit --warn-default-binding --warn-binding --warn-library --warn-body --warn-specs --warn-unused #{dependencies.join(" ")} #{@dut_path} #{@test_file.path}\n"
        f << "ghdl -e -Plibs/unisim --ieee=synopsys -fexplicit #{@test_file.test_name}\n"
        f << "ghdl -r #{@test_file.test_name} --vcd=out.vcd --stop-time=10ms\n"
      end
    end

    private
    def run_test
      @result = ""

      IO.popen("sh #{@sh} 2>&1") do |f|
        output = f.read
        @result << output
        @out << output
      end
    end

    def report_result
      formatter = ResultFormatter.new(@result)
      @out << "\n\n\n"
      @out << formatter.format
      unless formatter.compile_error?
        @out << "\n#{@test_file.cases.size} examples, #{formatter.count_failure} failures\n"
      end
      @out << "\nTest directory: #{@dir}\n"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Frontend::WebsHelper
end


text:
import torch
import io
import pandas as pd
import gc
import numpy as np
import transformers

class BertAoAHead(nn.Module):

    def __init__(self, config):

        super().__init__()
        self.hidden = config.hidden_size
        self.q_projection_1 = nn.Linear(config.hidden_size, 512)
        self.c_projection_1 = nn.Linear(config.hidden_size, 512)

        self.q_projection_2 = nn.Linear(config.hidden_size, 512)
        self.c_projection_2 = nn.Linear(config.hidden_size, 512)

    def forward(self, hidden_states, attention_mask):
        q_state, c_state = hidden_states[:, 1:2, :].clone(), hidden_states
        c_state[:, 0:2, :] = 0

        # take the question tokens and do linear projection to Qx1024
        q_state_1 = self.q_projection_1(q_state)
        q_state_2 = self.q_projection_2(q_state)

        # do the same for the context tokens for Cx1024
        c_state_1 = self.c_projection_1(c_state)
        c_state_2 = self.c_projection_2(c_state)

        # print("Q_state", q_state_1.shape)
        # print("C_state", c_state_2.shape)

        # perform matrix multiplication of the context and transposed question
        # Cx1024 * 1024xQ = CxQ
        M1 = torch.matmul(c_state_1, torch.transpose(q_state_1, 1, 2))
        M2 = torch.matmul(c_state_2, torch.transpose(q_state_2, 1, 2))
        # print("M", M1.shape)

        # make sure that padding wont affect the softmax
        M1[attention_mask != 1, :] = -999999
        M2[attention_mask != 1, :] = -999999

        # Softmax over the transposed result i.e softmax(QxC) = QxC
        alpha_1 = nn.functional.softmax(torch.transpose(M1, 1, 2), dim=2)
        alpha_2 = nn.functional.softmax(torch.transpose(M2, 1, 2), dim=2)
        # print("alpha", alpha_1)

        # Softmax over the result i.e softmax(CxQ) = CxQ
        beta_1 = nn.functional.softmax(M1, dim=2)
        beta_2 = nn.functional.softmax(M2, dim=2)
        # print("beta", beta_1)

        # Average sum(beta_1) by queries and divide by length and unsqeze CxQ ->  Qx1
        beta_1 = (torch.sum(beta_1, axis=1) / beta_1.size(1)).unsqueeze(1)
        beta_2 = (torch.sum(beta_2, axis=1) / beta_2.size(1)).unsqueeze(1)
        # print("beta sum", beta_1.shape)
        # print("beta", beta_1)

        # CxQ * Qx1 => Cx1 squeeze => C
        s1 = torch.matmul(torch.transpose(alpha_1, 1, 2), torch.transpose(beta_1, 1, 2)).squeeze(2)
        s2 = torch.matmul(torch.transpose(alpha_2, 1, 2),torch.transpose(beta_2, 1, 2)).squeeze(2)
        return s1, s2

'''

sudo apt update        # Fetches the list of available updates
sudo apt upgrade       # Installs some updates; does not remove packages
sudo apt full-upgrade  # Installs updates; may also remove some packages, if needed
sudo apt autoremove    # Removes any old packages that are no longer needed

Precision in our case would be how many images tagged as Spa are really Spa.
And Recall would be how many of the total Spa images have been tagged correctly.

Original Code Author [@dlibenzi](https://github.com/dlibenzi)
Complete Colab Example [link](https://colab.research.google.com/drive/1IvCxIg-Q_DlI7UNJuajpl4UZXNiW5jMg)
NB I have trimmed to what i felt was new to me as the idea, please refer to the colab
for the rest of the code blocks..

The code i tricky to understand if you have never worked with Files directly before;
Here on top of file handling concepts, it's  in binary format, so you need to be little more careful
with regards to writing and loading data..

Personal Notes
---------------

# A binary file is considered to be just a sequence of bytes - none of them has any special meaning,
# in the sense that a text-reader would interpret them..
# Basically binary files contain data and each individual byte can be an ascii character, an integer, a tensor etc.
# It's just how to write data to the file and how you rad it back.

# The io.BytesIO inherits from io.BufferedReader class comes with functions like read(), write(), peek(), getvalue().
# Binary data and strings are different types, so a str must be encoded to binary using ascii, utf-8, or other.
# It is a general buffer of bytes that you can work with.

# Seeking a specific position in a file

    You can move to a specific position in file before reading or writing using seek().
    You can pass a single parameter to seek() and it will move to that position, relative to the beginning of the file.

# Seek can be called one of two ways:
    #   x.seek(offset)
    #   x.seek(offset, starting_point)
    #   The offset is interpreted relative to the position indicated by whence

    # starting_point can be 0, 1, or 2
    # 0 - Default. Offset relative to beginning of file
    # 1 - Start from the current position in the file
    # 2 - Start from the end of a file (will require a negative offset)

i = 16
i.to_bytes(1, byteorder='big', signed=True)    # b'\x10' is an escape sequence that describes the byte with that hexadecimal value.
i.to_bytes(4, byteorder='big', signed=True)    # b'\x00\x00\x00\x10'
i.to_bytes(4, byteorder='little', signed=True) # b'\x10\x00\x00\x00'
b'\x00\xff' # Two bytes values 0 and 255

# https://docs.python.org/3/library/stdtypes.html#int.from_bytes

    If byteorder is "big", the most significant byte is at the beginning of the byte array.
    If byteorder is "little", the most significant byte is at the end of the byte array.

    # int.from_bytes(b'\x00\x10', byteorder='big')    # 16
    # int.from_bytes(b'\x00\x10', byteorder='little') # 4096

How can I read last 10 bytes from a text file ?? [solve it yourself first]

    # here's my sol
    f.seek(0, 2) # last byte
    nbytes = f.tell()
    f.seek(nbytes-10)
    last_ten = f.read(10)

# f.tell() Returns the current stream position.
# f.read(size=k) Read and return up to size bytes

# https://stackoverflow.com/questions/42800250/difference-between-open-and-io-bytesio-in-binary-streams
    when you use open(), The data wont be kept in memory after it's written to the file (unless being kept by a name).
    when you consider io.BytesIO() , Which instead of writing the contents to a file, it's written to an in memory buffer.
    In other words a chunk of RAM.
    # The key difference here is optimization and performance.

# save to a file
x = torch.tensor([0, 1, 2, 3, 4])
torch.save(x, 'tensor.pt')

# Save to io.BytesIO buffer
buffer = io.BytesIO()
torch.save(x, buffer)

# The getvalue() function just takes the value from the Buffer as a String
# and Return bytes containing the entire contents of the buffer.

'''

model="xlm-roberta-large"
batch_size=2
splits="8,16,32,64"
train_ds="train_dataset"
valid_ds="valid_dataset"

class FileDataset(object):
    def __init__(self, path):

        # open binary files to write to
        self._data_file = open(path + '.data', 'rb')
        self._index_file = open(path + '.index', 'rb')
        self._index_file.seek(0, 2)                # seek the last byte of the file
        self._index_size = self._index_file.tell() # size of the current stream position, Basically Get the file size...
        assert self._index_size % 8 == 0
        self._data_file.seek(0, 2)                 # seek the last byte of the file
        self._data_size = self._data_file.tell()   # size of the current stream position, Basically Get the file size...

    def read_sample(self, idx):
        '''
        The idea is basically that first you seek next 8 bytes from your current position (where ever you are in the file).
        After that you check that whether we can get the next's next whole 8 bytes as well; (so it's current + 16).
        If we can, then we calculate the next offset.
        '''
        index_offset = idx * 8
        assert index_offset < self._index_size
        self._index_file.seek(index_offset) # move to this position relative to the beginning of the file
        data_offset = int.from_bytes(self._index_file.read(8), byteorder='little') # read eight_bytes in little endian byte order
        if index_offset + 16 <= self._index_size:
            next_offset = int.from_bytes(self._index_file.read(8), byteorder='little') # next 8 bytes set-up for next seek
        else:
            next_offset = self._data_size  # else set it to end of the file
        self._data_file.seek(data_offset)  # move to this position relative to the beginning of the file wrt data file
        sample_data = self._data_file.read(next_offset - data_offset) # read these many
        return torch.load(io.BytesIO(sample_data)) # return as a tensor

    def get_num_samples(self):
        return self._index_size // 8

def bytes_from_file(fname, ck_sz=8192):
    '''
    simple func to stream bytes from the given file
    '''
    with open(fname, "rb") as f:
        while True:
            chunk = f.read(ck_sz)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

def regular_encode_on_fly(texts, tokenizer, splits):
    '''
    pad only to the length that's needed to make the batch padded to same length
    aka bucketing
    '''
    max_len = max(len(x.split()) for x in texts)
    for l in splits:
      if l >= max_len:
        max_len = l
        break
    max_len = min(max_len, splits[-1])
    enc_di = tokenizer.batch_encode_plus(
        texts,
        add_special_tokens=True,
        return_attention_masks=True,
        return_token_type_ids=False,
        pad_to_max_length=True,
        max_length=max_len,
    )
    return np.array(enc_di['input_ids']), np.array(enc_di["attention_mask"])

def indices_for_ordinal(ordinal, world_size, count, shuffle=True):
    '''
    it's a 3 line sampler;
    ordinal denotes TPU_IDX
    world_size denotes how many TPU_CORES
    count denotes the #samples you have in your dataset file
    '''
    count = (count // world_size) * world_size
    indices = list(range(ordinal, count, world_size)) # start:end:step_size
    if shuffle:
        np.random.shuffle(indices)
    return indices

def prep_data(bs, df):
    '''
    basically the idea is to create the batches ourselves;
    NB we are using dynamic padding here (splits variable);
    '''
    sentences = df['comment_text'].astype(str).values
    sort_idx = np.argsort(np.array([len(x.split()) for x in sentences]))
    sentences = sentences[sort_idx]
    targets = df['toxic'].values[sort_idx]
    num_samples = (len(sentences) // bs) * bs
    sentences = sentences[: num_samples]
    targets = targets[: num_samples]
    return sentences.reshape(len(sentences) // bs, bs), targets.reshape(len(targets) // bs, bs)

def write_sample(s, data_file, index_file):
    bio = io.BytesIO() # get a buffer
    torch.save(s, bio) # save it to the buffer
    offset = data_file.tell() # [int] what's the current position of the "data_file" stream
    index_file.write((offset).to_bytes(8, byteorder='little')) # write the index for this tensor batch
    data_file.write(bio.getvalue())

def create_dataset(df, tokenizer, batch_size, splits, path):
    x, y = prep_data(batch_size, df) # grab the batches (raw-text, targets)
    xt = [torch.tensor(regular_encode_on_fly(t, tokenizer, splits)) for t in x] # converting them to tokens; each batch is dynamically padded
    yt = [torch.tensor(t, dtype=torch.float) for t in y] # targets
    with open(path + '.data', 'wb') as data_file:
        with open(path + '.index', 'wb') as index_file:
            for s in zip(xt, yt):
                # since we are using zip, so it's packing the items from x and y respectively together;
                write_sample(s, data_file, index_file)

def generate_index():
    global splits
    tokenizer = transformers.XLMRobertaTokenizer.from_pretrained(model)

    train1 = pd.read_csv(
        './jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv',
        usecols=["comment_text", "toxic"],
        nrows = 8
    )

    all_train = train1[['comment_text', 'toxic']]

    del train1
    gc.collect(); gc.collect();

    all_train = all_train.sample((all_train.shape[0]//batch_size)*batch_size)

    print('DF:', all_train.shape,)

    splits = sorted([int(x) for x in splits.split(',')])
    create_dataset(all_train, tokenizer, batch_size, splits, train_ds)

if __name__== "__main__":
    generate_index()


text:
.. _refcard_services:
.. module:: pelix.framework

Services
========

A service is an object that is registered to the service registry of the
framework, associated to a set of specifications it implements and to
properties.

The bundle that registers the service must keep track of the
:class:`~ServiceRegistration` object returned by the framework.
It allows to update the service properties and to unregister the service.
This object **shall not** be accessible by other bundles/services, as it gives
access and control over the life cycle of the service it represents.
Finally, all services must be unregistered when their bundle is stopped.

A consumer can look for a service that matches a specification and a set of
properties, using its :class:`~BundleContext`.
The framework will return a :class:`~ServiceReference` object, which provides a
read-only access to the description of its associated service:
properties, registering bundle, bundles using it, etc..

Properties
----------

When registered and while it is available, the properties of a service can be
set and updated by its provider.

Although, some properties are reserved for the framework; each service has at
least the following properties:

=========== =========== =======================================================
Name        Type        Description
=========== =========== =======================================================
objectClass list of str List of the specifications implemented by this service
service.id  int         Identifier of the service. Unique in a framework instance
=========== =========== =======================================================

The framework also uses the following property to sort the result of a service look up:

=============== ==== ==========================================================
Name            Type Description
=============== ==== ==========================================================
service.ranking int  The rank/priority of the service. The lower the rank, the more priority
=============== ==== ==========================================================

.. _service_factory:

Service Factory
---------------

.. warning:: Service factories are a very recent feature of iPOPO and might be
   prone to bugs: please report any bug encounter on
   the `project GitHub <https://github.com/tcalmant/ipopo/issues>`_.

A service factory is a pseudo-service with a specific flag, which can create
individual instances of service objects for different bundles.
Sometimes a service needs to be differently configured depending on which
bundle uses the service.
For example, the log service needs to be able to print the logging bundle's id,
otherwise the log would be hard to read.

A service factory is registered in exactly the same way as a normal service,
using :meth:`~pelix.framework.BundleContext.register_service`, with the
``factory`` argument set to ``True``.
The only difference is an indirection step before the actual service object is
handed out.

The client using the service need not, and should not, care if a service is
generated by a factory or by a plain object.

A simple service factory example

.. code-block:: python

    class ServiceInstance:
        def __init__(self, value):
            self.__value = value

        def cleanup(self):
            self.__value = None

        def get_value(self):
            return self.__value

    class ServiceFactory:
        def __init__(self):
            # Bundle -> Instance
            self._instances = {}

        def get_service(self, bundle, registration):
            """
            Called each time a new bundle requires the service
            """
            instance = ServiceInstance(bundle.get_bundle_id())
            self._instances[bundle] = instance
            return instance

        def unget_service(self, bundle, registration):
            """
            Called when a bundle has released all its references
            to the service
            """
            # Release connections, ...
            self._instances.pop(bundle).cleanup()

    bundle_context.register_service(
        "sample.factory", ServiceFactory(), {}, factory=True)

.. note:: The framework will cache generated service objects.
   Thus, at most one service can be generated per client bundle.

Prototype Service Factory
-------------------------

.. warning:: Prototype Service factories are a very recent feature of iPOPO
   and might be prone to bugs: please report any bug encounter on
   the `project GitHub <https://github.com/tcalmant/ipopo/issues>`_.

A prototype service factory is a pseudo-service with a specific flag, which can
create multiple instances of service objects for different bundles.

Each time a bundle requires the service, the prototype service factory is
called and can return a different instance.
When called, the framework gives the factory the :class:`~Bundle` object
requesting the service and the :class:`~ServiceRegistration` of the requested
service.
This allows a single factory to be registered for multiple services.

Note that there is no Prototype Service Factory implemented in the core
Pelix/iPOPO Framework (unlike the *Log Service* *simple* service factory).

A Prototype Service Factory is registered in exactly the same way as a normal
service, using :meth:`~pelix.framework.BundleContext.register_service`,
with the ``prototype`` argument set to ``True``.

A simple prototype service factory example:

.. code-block:: python

    class ServiceInstance:
        def __init__(self, value):
            self.__value = value

        def cleanup(self):
            self.__value = None

        def get_value(self):
            return self.__value

    class PrototypeServiceFactory:
        def __init__(self):
            # Bundle -> [instances]
            self._instances = {}

        def get_service(self, bundle, registration):
            """
            Called each time ``get_service()`` is called
            """
            bnd_instances = self._instances.setdefault(bundle, [])
            instance = ServiceInstance(
                [bundle.get_bundle_id(), len(bnd_instances)])
            bnd_instances.append(instance)
            return instance

        def unget_service_instance(self, bundle, registration, service):
            """
            Called when a bundle releases an instance of the service
            """
            bnd_instances[bundle].remove(service)
            service.cleanup()

        def unget_service(self, bundle, registration):
            """
            Called when a bundle has released all its references
            to the service
            """
            # Release global resources...

            # When this method is called, all instances will have been cleaned
            # up individually in ``unget_service_instance``
            if len(self._instances.pop(bundle)) != 0:
               raise ValueError("Should never happen")

    bundle_context.register_service(
        "sample.proto", PrototypeServiceFactory(), {}, factory=True)

.. note:: A Prototype Service Factory is considered as a Service Factory, hence
   both :meth:`~ServiceReference.is_factory` and
   :meth:`~ServiceReference.is_prototype` will return ``True`` for this kind
   of service

API
---

The service provider has access to the :class:`~ServiceRegistration` object
created by the framework when :meth:`~BundleContext.register_service` is
called.

.. autoclass:: ServiceRegistration
   :members:

Consumers can access the service using its :class:`~ServiceReference` object,
unique and constant for each service.
This object can be retrieved using the :class:`~BundleContext` and its
``get_service_reference*`` methods.
A consumer can check the properties of a service through this object, before
consuming it.

.. autoclass:: ServiceReference
   :members: get_bundle, get_properties, get_property, get_property_keys,
             get_using_bundles, is_factory, is_prototype

Finally, here are the methods of the :ref:`BundleContext <api_bundlecontext>`
class that can be used to handle services:

.. autoclass:: BundleContext
   :noindex:
   :members: add_service_listener, remove_service_listener,
             get_all_service_references, get_service, get_service_reference,
             get_service_references, register_service, unget_service


text:
'use strict';

const chai = require('chai');

describe('Test environment Health-check', () => {
  it('Test chai to be an object', () => {
     chai.expect(chai).to.be.an('object');
  });
});


text:
{-# LANGUAGE ExistentialQuantification           #-}
{-# LANGUAGE MultiWayIf, RankNTypes, BangPatterns#-}
module Web.Haskyapi.Console.Cli (
  haskyapi,
  haskyapiM,
  argparse,
  Option(..),
  Mode(..),
) where

import System.Directory (getDirectoryContents)
import System.Environment (getArgs)
-- import System.Exit
import Control.Monad.State
import Control.Applicative ((<$>))
-- import qualified Data.List.Split as L
import qualified Data.List       as L
import Data.Maybe (fromMaybe)
import Data.Map ((!))

import qualified Web.Haskyapi.Config.Config as Config
import Web.Haskyapi.Config.Defaults (defs)
import Web.Haskyapi (runServer)
import Web.Haskyapi.Header (Api)

--------------------------------------------------------
-- command option
--------------------------------------------------------
-- haskyapi --help
-- haskyapi --version
-- haskyapi migrate
-- haskyapi migrate --help
-- haskyapi runserver --help
-- haskyapi runserver --root ... --port ... --ip ...
--------------------------------------------------------

data Mode a = Runserver a
            | Migrate   a
            | Message String
            | Error String
            deriving (Show)

mode2str :: Mode a -> String
mode2str (Runserver _) = "haskyapi runserver\n"
mode2str (Migrate   _) = "haskyapi migrate\n"
mode2str (Message   _) = "message"
mode2str (Error     _) = "error"

instance Functor Mode where
  fmap f  (Runserver x) = Runserver (f x)
  fmap f  (Migrate x)   = Migrate (f x)
  fmap _f (Message x)   = Message x
  fmap _  (Error x)     = Error x

data Arg = Arg {
             key   :: [String],
             def   :: String,
             name  :: String,
             description :: String
         }

type A = (String, String)

data Option = OptRunserver {
                oport :: String,
                oroot :: String,
                oip   :: String
              }
            | OptMigrate
            deriving (Show)

argConfMigrate :: [Arg]
argConfMigrate = [
     Arg ["-h", "--help"] "...."      "help" "Help"
  ]

argConfRunserver :: [Arg]
argConfRunserver = [
     Arg ["-p", "--port"] (defs ! "port") "port" "Port number"
    ,Arg ["-i", "--ip"  ] (defs ! "ip")   "ip"   "IP"
    ,Arg ["-r", "--root"] "html"          "root" "Root directory"
    ,Arg ["-h", "--help"] "...."          "help" "Help"
  ]

verMessage = "haskyapi version 0.0.0.1"

argparse :: [String] -> Mode Option
argparse args =
  case checkmode args of
    Error x      -> Error x
    Message x    -> Message x
    Runserver xs -> argparseMain argConfRunserver xs Runserver
    Migrate   xs -> argparseMain argConfMigrate   xs Migrate
  where
    checkmode :: [String] -> Mode [String]
    checkmode ("runserver":xs) = Runserver xs
    checkmode ("migrate"  :xs) = Migrate xs
    checkmode ("--version":_)  = Message verMessage
    checkmode ("-v":_)         = Message verMessage
    checkmode ("--help":_)     = Message mkHelpAll
    checkmode ("-h":_)         = Message mkHelpAll
    checkmode _                = Error "invalid mode!!"
    mkHelpAll :: String
    mkHelpAll = mkHelp [("haskyapi migrate\n", argConfMigrate), ("haskyapi runserver\n", argConfRunserver)]
    mkHelp lst = concat $ foldl (\l (x,y) -> [x, aux y] ++ l ) [] lst
      where
        aux = unlines . map aux'
        -- Arg's Example => Arg ["-p", "--port"] "8080" "port" "Port number"
        aux' (Arg forms defa nm desc) = L.intercalate "\t" [ "\t" ++ eqleng 6 nm,
                                                             eqleng 11 (unwords forms),
                                                             "defaulut = " ++ eqleng 8 defa,
                                                             desc
                                                           ]
        eqleng th xs =
          let !l = length xs in
          if | length xs <= th -> xs ++ replicate (th-l) ' '
             | otherwise       -> xs
    argparseMain :: [Arg] -> [String] -> ([A] -> Mode [A]) -> Mode Option
    argparseMain argconf xs mode = a2optMain $ execState (argparse' xs) (mode [])
      where
        argparse' :: [String] -> State (Mode [A]) ()
        argparse' [] = return ()
        argparse' ("-h":_)        = modify $ \_ -> Message $ mkHelp [(mode2str (mode []), argconf)]
        argparse' ("--help":_)    = modify $ \_ -> Message $ mkHelp [(mode2str (mode []), argconf)]
        argparse' [x]             = modify $ \_ -> Error ("error near " ++ x)
        argparse' (ag:x:xs) =
          case filter (elem ag . key) argconf of
            [a] -> modify (fmap ((name a, x):)) >> argparse' xs
            _   -> modify $ \_ -> Error ("invalid argument " ++ ag)
        a2optMain :: Mode [A] -> Mode Option
        a2optMain (Runserver as) = Runserver (a2opt as)
        a2optMain (Migrate  _as) = Migrate OptMigrate
        a2optMain (Message x)    = Message x
        a2optMain (Error x)      = Error x
        a2opt :: [A] -> Option
        a2opt as = execState (aux argconf) (OptRunserver "" "" "")
          where
            aux :: [Arg] -> State Option ()
            aux [] = return ()
            aux (acf:acfs) =
              let nm = name acf
                  a  = fromMaybe (def acf) $ lookup (name acf) as in
              if | nm == "port" -> modify (\x -> x { oport = a }) >> aux acfs
                 | nm == "root" -> modify (\x -> x { oroot = a }) >> aux acfs
                 | nm == "ip"   -> modify (\x -> x { oip   = a }) >> aux acfs
                 | otherwise    -> aux acfs

-- Main command which users' applications call
haskyapi :: [Api] -> IO ()
haskyapi routing = haskyapiM routing (return ())

haskyapiM :: [Api] -> IO () -> IO ()
haskyapiM routing migrate = do
  args <- getArgs
  case argparse args of
    Error x ->
      putStrLn x
    Message x ->
      putStrLn x
    Runserver opt ->
      mainProc opt
    Migrate _opt ->
      migrate
  where
    mainProc :: Option -> IO ()
    mainProc !opt = do
      -- Config.hoge has a default value, and arguments.hoge also has the same default value.
      -- Default values are defined in '../Config/Defaults.hs'
      cpo <- Config.port
      cip <- Config.ip
      csd <- Config.subdomain
      let
        !root = oroot opt
        !_ip  = oip   opt
        !_po  = oport opt
        !ip   = if _ip == (defs ! "ip")   then cip else _ip
        !port = if _po == (defs ! "port") then cpo else _po
        !url  = "http://" ++ ip ++ ":" ++ port ++ "/"
      putStrLn $ "root: "     ++ root
      putStrLn $ "listen on " ++ port
      putStrLn url
      mapM_ (putStrLn . \h -> url ++ h) =<< getfiles root
      runServer (port, root, ip, csd, routing)
      where
        getfiles :: FilePath -> IO [FilePath]
        getfiles root =
          filter aux <$> getDirectoryContents root
          where
            aux ('.':_) = False
            aux _ = True

-- main = do
--   print $ argparse ["runserver", "--root", "html"]
--   print $ argparse ["migrate", "--help"]
--   let Message a = argparse ["runserver", "--help"]
--   putStrLn a
--   print $ argparse ["migrate"]
--   print $ argparse ["-v"]


text:
<?php
    // Start the session
    if(!isset($_SESSION)) {
        session_start();
    }
    //$_SESSION["username"] = null;
    //$_SESSION["fname"] = null;
    //$_SESSION["lname"] = null;
    //$_SESSION["email"] = null;
    //$_SESSION["fname"] = null;
    //$_SESSION["user"] = "von";
?>
<!DOCTYPE HTML>

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

    <title>Christian's Blog</title>

    <link rel="stylesheet" href="<?php echo base_url().'application/styles/reset.css'; ?>" type="text/css" media="screen, projection, handheld">

    <link rel="stylesheet" href="<?php echo base_url().'application/styles/jquery/jquery-ui.css'; ?>" type="text/css" media="screen, projection, handheld">

    <link rel="stylesheet" href="<?php echo base_url().'application/styles/css/bootstrap.css'; ?>" type="text/css" media="screen, projection, handheld">

    <?php
        if(isset($_SESSION["username"])) {
            echo "<link rel='stylesheet' href='".base_url()."application/styles/".$_SESSION["theme"].".css' type='text/css' media='screen, projection, handheld'>";
        }
        else {
            echo "<link rel='stylesheet' href='".base_url()."application/styles/stylesheet.css' type='text/css' media='screen, projection, handheld'>";
        }
    ?>

All form fields are required.

        <form>
            <fieldset>
                Username:
                <input type="text" name="username" id="username" value="" class="text ui-widget-content ui-corner-all">

                Password:
                <input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all">

                <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
            </fieldset>
        </form>

All form fields are required.

        <form>
            <fieldset>
                Username:
                <input type="text" name="usernamec" id="usernamec" value="" class="text ui-widget-content ui-corner-all">

                First Name:
                <input type="text" name="fname" id="fname" value="" class="text ui-widget-content ui-corner-all">

                Last Name:
                <input type="text" name="lname" id="lname" value="" class="text ui-widget-content ui-corner-all">

                Email
                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all">

                Password:
                <input type="password" name="passwordc" id="passwordc" value="" class="text ui-widget-content ui-corner-all">

                <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
            </fieldset>
        </form>

CptS 483 Final

Christian Webber's Blog

<button id='home_btn'>Home</button>     <button id='post_btn'>Posts</button>      <button id='game_btn'>Games</button>
        <?php
        if (isset($_SESSION["username"]))
        {
            echo 'Hello '.$_SESSION["fname"];

            if ($_SESSION["rank"] < 3)
            {
                echo "     ";
                echo "<button id='admin_btn'>Administration</button>";
            }

            echo "     ";
            echo "<button id='edit_btn'>Account Settings</button>";

            echo "     <button id='logout_btn'>Logout</button>";
        }
        else
        {
            echo "<button id='login_btn'>Login</button>     <button id='create_btn'>Create Account</button>";
        }

        ?>


text:
using System;
using Hik.Communication.Scs.Communication.Messages;

namespace Hik.Communication.ScsServices.Communication.Messages
{
    /// <summary>
    /// This message is sent as response message to a ScsRemoteInvokeMessage.
    /// It is used to send return value of method invocation.
    /// </summary>
    [Serializable]
    public class ScsRemoteInvokeReturnMessage : ScsMessage
    {
        /// <summary>
        /// Return value of remote method invocation.
        /// </summary>
        public object ReturnValue { get; set; }

        /// <summary>
        /// If any exception occured during method invocation, this field contains Exception object.
        /// If no exception occured, this field is null.
        /// </summary>
        public ScsRemoteException RemoteException { get; set; }

        /// <summary>
        /// Represents this object as string.
        /// </summary>
        /// <returns>String representation of this object</returns>
        public override string ToString()
        {
            return string.Format("ScsRemoteInvokeReturnMessage: Returns {0}, Exception = {1}", ReturnValue, RemoteException);
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>pzalejko.iot.hardware</groupId>
		<artifactId>pzalejko.iot.hardware</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>pzalejko.iot.hardware.led.mqqt.example</artifactId>

	<properties>
		<main.class.name>pzalejko.iot.hardware.led.mqqt.example.Main</main.class.name>
	</properties>

	<dependencies>
		<dependency>
			<groupId>openjdk</groupId>
			<artifactId>dio</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.paho</groupId>
			<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>${main.class.name}</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
<!DOCTYPE html>

		<meta charset="UTF-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

		<title>The Quest for the Perfect Cookie</title>
		<link rel="stylesheet" href="styles.css"/>

Supplies

Kitchen Equipment

1 large mixing bowl

1 large mixing spoon

1 or more cookie baking sheets

1 set of measuring cups

1 set of measuring spoons

1 electric mixer (optional)

1 cooling rack (optional)

Cookie Ingredients

1 teaspoon baking soda

1 teaspoon salt

1 cup (2 sticks) butter, softened

3/4 cup granulated sugar

3/4 cup packed brown sugar

1 teaspoon vanilla extract

2 large eggs

2 cups (12-oz. pkg.) semi-sweet chocolate morsels

2 1/4 cups all-purpose flour

Back

Continue


text:
package forest

// Logf adds the actual file:line information to the log message
func Logf(t T, format string, args ...interface{}) {
	t.Helper()
	t.Logf(format, args...)
	//logf_func(t, noStackOffset, "\n"+format, args...)
}

func logfatal(t T, format string, args ...interface{}) {
	t.Helper()
	t.Logf(format, args...)
	t.FailNow()
}

func logerror(t T, format string, args ...interface{}) {
	t.Helper()
	t.Logf(format, args...)
	t.Fail()
}


text:
function evaluateSexprs(context, params, types, helpers) {
  var sexprSpec, i, len;
  for (i = 0, len = params.length; i < len; ++i) {
    if (types[i] === 'sexpr') {
      sexprSpec = params[i];
      sexprSpec[2].helpers = helpers; // TODO seems like this should be compiled in, no?
      params[i] = helpers.RESOLVE(context, sexprSpec[0], sexprSpec[1], sexprSpec[2]);
    }
  }
}

function evaluateHashSexprs(context, hash, hashTypes, helpers) {
  var k, sexprSpec;
  for (k in hash) {
    if (hash.hasOwnProperty(k) && hashTypes[k] === 'sexpr') {
      sexprSpec = hash[k];
      sexprSpec[2].helpers = helpers; // TODO seems like this should be compiled in, no?
      hash[k] = helpers.RESOLVE(context, sexprSpec[0], sexprSpec[1], sexprSpec[2]);
    }
  }
}

export function RESOLVE(context, path, params, options) {
  var helper = options.helpers[path];

  // TODO: use something like RESOLVE_HELPER to allow late-binding.
  if (helper) {

    evaluateSexprs(context, params, options.types, options.helpers);
    evaluateHashSexprs(context, options.hash, options.hashTypes, options.helpers);

    var ret = helper(context, params, options);
    if (ret && options.placeholder) {
      options.placeholder.appendText(ret);
    }
    return ret;
  } else {
    var value = context[path];

    if (options.escaped) {
      options.placeholder.appendText(value);
    } else {
      options.placeholder.appendHTML(value);
    }
  }
}

export function RESOLVE_IN_ATTR(context, path, params, options) {
  var helpers = options.helpers,
      helper = helpers[path];

  if (helper) {
    return helper(context, params, options);
  } else {
    return context[path];
  }
}

export function ATTRIBUTE(context, name, params, options) {

  var helpers = options.helpers,
      buffer = [];

  params.forEach(function(node) {
    if (typeof node === 'string') {
      buffer.push(node);
    } else {
      var helperOptions = node[2];
      helperOptions.helpers = helpers;
      var ret = helpers.RESOLVE_IN_ATTR(context, node[0], node[1], helperOptions);
      if (ret) { buffer.push(ret); }
    }
  });

  if (buffer.length) {
    options.element.setAttribute(name, buffer.join(''));
  }
}


text:
#ifndef BOOST_OUTCOME_SYSTEM_ERROR2_GENERIC_CODE_HPP
#define BOOST_OUTCOME_SYSTEM_ERROR2_GENERIC_CODE_HPP

#include "status_error.hpp"

#include <cerrno>  // for error constants

BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_BEGIN

//! The generic error coding (POSIX)
enum class errc : int
{
  success = 0,
  unknown = -1,

  address_family_not_supported = EAFNOSUPPORT,
  address_in_use = EADDRINUSE,
  address_not_available = EADDRNOTAVAIL,
  already_connected = EISCONN,
  argument_list_too_long = E2BIG,
  argument_out_of_domain = EDOM,
  bad_address = EFAULT,
  bad_file_descriptor = EBADF,
  bad_message = EBADMSG,
  broken_pipe = EPIPE,
  connection_aborted = ECONNABORTED,
  connection_already_in_progress = EALREADY,
  connection_refused = ECONNREFUSED,
  connection_reset = ECONNRESET,
  cross_device_link = EXDEV,
  destination_address_required = EDESTADDRREQ,
  device_or_resource_busy = EBUSY,
  directory_not_empty = ENOTEMPTY,
  executable_format_error = ENOEXEC,
  file_exists = EEXIST,
  file_too_large = EFBIG,
  filename_too_long = ENAMETOOLONG,
  function_not_supported = ENOSYS,
  host_unreachable = EHOSTUNREACH,
  identifier_removed = EIDRM,
  illegal_byte_sequence = EILSEQ,
  inappropriate_io_control_operation = ENOTTY,
  interrupted = EINTR,
  invalid_argument = EINVAL,
  invalid_seek = ESPIPE,
  io_error = EIO,
  is_a_directory = EISDIR,
  message_size = EMSGSIZE,
  network_down = ENETDOWN,
  network_reset = ENETRESET,
  network_unreachable = ENETUNREACH,
  no_buffer_space = ENOBUFS,
  no_child_process = ECHILD,
  no_link = ENOLINK,
  no_lock_available = ENOLCK,
  no_message = ENOMSG,
  no_protocol_option = ENOPROTOOPT,
  no_space_on_device = ENOSPC,
  no_stream_resources = ENOSR,
  no_such_device_or_address = ENXIO,
  no_such_device = ENODEV,
  no_such_file_or_directory = ENOENT,
  no_such_process = ESRCH,
  not_a_directory = ENOTDIR,
  not_a_socket = ENOTSOCK,
  not_a_stream = ENOSTR,
  not_connected = ENOTCONN,
  not_enough_memory = ENOMEM,
  not_supported = ENOTSUP,
  operation_canceled = ECANCELED,
  operation_in_progress = EINPROGRESS,
  operation_not_permitted = EPERM,
  operation_not_supported = EOPNOTSUPP,
  operation_would_block = EWOULDBLOCK,
  owner_dead = EOWNERDEAD,
  permission_denied = EACCES,
  protcol_error = EPROTO,
  protocol_not_supported = EPROTONOSUPPORT,
  read_only_file_system = EROFS,
  resource_deadlock_would_occur = EDEADLK,
  resource_unavailable_try_again = EAGAIN,
  result_out_of_range = ERANGE,
  state_not_recoverable = ENOTRECOVERABLE,
  stream_timeout = ETIME,
  text_file_busy = ETXTBSY,
  timed_out = ETIMEDOUT,
  too_many_files_open_in_system = ENFILE,
  too_many_files_open = EMFILE,
  too_many_links = EMLINK,
  too_many_symbolic_link_levels = ELOOP,
  value_too_large = EOVERFLOW,
  wrong_protocol_type = EPROTOTYPE
};

namespace detail
{
  struct generic_code_messages
  {
    // libc++ defines missing errc macros to integers in the 9xxx range
    // As much as 10,000 seems wasteful, bear in mind this is all constexpr
    // and on C++ 14 or later this entire construct disappears.
    const char *msgs[(ETIME >= 256) ? 10000 : 256];
    BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 size_t size() const { return sizeof(msgs) / sizeof(*msgs); }  // NOLINT
    BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 const char *operator[](int i) const { return (i < 0 || i >= static_cast<int>(size()) || nullptr == msgs[i]) ? "unknown" : msgs[i]; }  // NOLINT
    BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 generic_code_messages()
        : msgs{}
    {
      msgs[0] = "Success";

      msgs[EAFNOSUPPORT] = "Address family not supported by protocol";
      msgs[EADDRINUSE] = "Address already in use";
      msgs[EADDRNOTAVAIL] = "Cannot assign requested address";
      msgs[EISCONN] = "Transport endpoint is already connected";
      msgs[E2BIG] = "Argument list too long";
      msgs[EDOM] = "Numerical argument out of domain";
      msgs[EFAULT] = "Bad address";
      msgs[EBADF] = "Bad file descriptor";
      msgs[EBADMSG] = "Bad message";
      msgs[EPIPE] = "Broken pipe";
      msgs[ECONNABORTED] = "Software caused connection abort";
      msgs[EALREADY] = "Operation already in progress";
      msgs[ECONNREFUSED] = "Connection refused";
      msgs[ECONNRESET] = "Connection reset by peer";
      msgs[EXDEV] = "Invalid cross-device link";
      msgs[EDESTADDRREQ] = "Destination address required";
      msgs[EBUSY] = "Device or resource busy";
      msgs[ENOTEMPTY] = "Directory not empty";
      msgs[ENOEXEC] = "Exec format error";
      msgs[EEXIST] = "File exists";
      msgs[EFBIG] = "File too large";
      msgs[ENAMETOOLONG] = "File name too long";
      msgs[ENOSYS] = "Function not implemented";
      msgs[EHOSTUNREACH] = "No route to host";
      msgs[EIDRM] = "Identifier removed";
      msgs[EILSEQ] = "Invalid or incomplete multibyte or wide character";
      msgs[ENOTTY] = "Inappropriate ioctl for device";
      msgs[EINTR] = "Interrupted system call";
      msgs[EINVAL] = "Invalid argument";
      msgs[ESPIPE] = "Illegal seek";
      msgs[EIO] = "Input/output error";
      msgs[EISDIR] = "Is a directory";
      msgs[EMSGSIZE] = "Message too long";
      msgs[ENETDOWN] = "Network is down";
      msgs[ENETRESET] = "Network dropped connection on reset";
      msgs[ENETUNREACH] = "Network is unreachable";
      msgs[ENOBUFS] = "No buffer space available";
      msgs[ECHILD] = "No child processes";
      msgs[ENOLINK] = "Link has been severed";
      msgs[ENOLCK] = "No locks available";
      msgs[ENOMSG] = "No message of desired type";
      msgs[ENOPROTOOPT] = "Protocol not available";
      msgs[ENOSPC] = "No space left on device";
      msgs[ENOSR] = "Out of streams resources";
      msgs[ENXIO] = "No such device or address";
      msgs[ENODEV] = "No such device";
      msgs[ENOENT] = "No such file or directory";
      msgs[ESRCH] = "No such process";
      msgs[ENOTDIR] = "Not a directory";
      msgs[ENOTSOCK] = "Socket operation on non-socket";
      msgs[ENOSTR] = "Device not a stream";
      msgs[ENOTCONN] = "Transport endpoint is not connected";
      msgs[ENOMEM] = "Cannot allocate memory";
      msgs[ENOTSUP] = "Operation not supported";
      msgs[ECANCELED] = "Operation canceled";
      msgs[EINPROGRESS] = "Operation now in progress";
      msgs[EPERM] = "Operation not permitted";
      msgs[EOPNOTSUPP] = "Operation not supported";
      msgs[EWOULDBLOCK] = "Resource temporarily unavailable";
      msgs[EOWNERDEAD] = "Owner died";
      msgs[EACCES] = "Permission denied";
      msgs[EPROTO] = "Protocol error";
      msgs[EPROTONOSUPPORT] = "Protocol not supported";
      msgs[EROFS] = "Read-only file system";
      msgs[EDEADLK] = "Resource deadlock avoided";
      msgs[EAGAIN] = "Resource temporarily unavailable";
      msgs[ERANGE] = "Numerical result out of range";
      msgs[ENOTRECOVERABLE] = "State not recoverable";
      msgs[ETIME] = "Timer expired";
      msgs[ETXTBSY] = "Text file busy";
      msgs[ETIMEDOUT] = "Connection timed out";
      msgs[ENFILE] = "Too many open files in system";
      msgs[EMFILE] = "Too many open files";
      msgs[EMLINK] = "Too many links";
      msgs[ELOOP] = "Too many levels of symbolic links";
      msgs[EOVERFLOW] = "Value too large for defined data type";
      msgs[EPROTOTYPE] = "Protocol wrong type for socket";
    }
  };
}  // namespace detail

/*! The implementation of the domain for generic status codes, those mapped by `errc` (POSIX).
*/
class _generic_code_domain : public status_code_domain
{
  template <class> friend class status_code;
  template <class StatusCode> friend class detail::indirecting_domain;
  using _base = status_code_domain;

public:
  //! The value type of the generic code, which is an `errc` as per POSIX.
  using value_type = errc;
  using string_ref = _base::string_ref;

public:
  //! Default constructor
  constexpr explicit _generic_code_domain(typename _base::unique_id_type id = 0x746d6354f4f733e9) noexcept : _base(id) {}
  _generic_code_domain(const _generic_code_domain &) = default;
  _generic_code_domain(_generic_code_domain &&) = default;
  _generic_code_domain &operator=(const _generic_code_domain &) = default;
  _generic_code_domain &operator=(_generic_code_domain &&) = default;
  ~_generic_code_domain() = default;

  //! Constexpr singleton getter. Returns the constexpr generic_code_domain variable.
  static inline constexpr const _generic_code_domain &get();

  virtual _base::string_ref name() const noexcept override { return string_ref("generic domain"); }  // NOLINT
protected:
  virtual bool _do_failure(const status_code<void> &code) const noexcept override  // NOLINT
  {
    assert(code.domain() == *this);  // NOLINT
    return static_cast<const generic_code &>(code).value() != errc::success;  // NOLINT
  }
  virtual bool _do_equivalent(const status_code<void> &code1, const status_code<void> &code2) const noexcept override  // NOLINT
  {
    assert(code1.domain() == *this);  // NOLINT
    const auto &c1 = static_cast<const generic_code &>(code1);  // NOLINT
    if(code2.domain() == *this)
    {
      const auto &c2 = static_cast<const generic_code &>(code2);  // NOLINT
      return c1.value() == c2.value();
    }
    return false;
  }
  virtual generic_code _generic_code(const status_code<void> &code) const noexcept override  // NOLINT
  {
    assert(code.domain() == *this);  // NOLINT
    return static_cast<const generic_code &>(code);  // NOLINT
  }
  virtual _base::string_ref _do_message(const status_code<void> &code) const noexcept override  // NOLINT
  {
    assert(code.domain() == *this);  // NOLINT
    const auto &c = static_cast<const generic_code &>(code);  // NOLINT
    static BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 detail::generic_code_messages msgs;
    return string_ref(msgs[static_cast<int>(c.value())]);
  }
#if defined(_CPPUNWIND) || defined(__EXCEPTIONS) || defined(BOOST_OUTCOME_STANDARDESE_IS_IN_THE_HOUSE)
  BOOST_OUTCOME_SYSTEM_ERROR2_NORETURN virtual void _do_throw_exception(const status_code<void> &code) const override  // NOLINT
  {
    assert(code.domain() == *this);  // NOLINT
    const auto &c = static_cast<const generic_code &>(code);  // NOLINT
    throw status_error<_generic_code_domain>(c);
  }
#endif
};
//! A specialisation of `status_error` for the generic code domain.
using generic_error = status_error<_generic_code_domain>;
//! A constexpr source variable for the generic code domain, which is that of `errc` (POSIX). Returned by `_generic_code_domain::get()`.
constexpr _generic_code_domain generic_code_domain;
inline constexpr const _generic_code_domain &_generic_code_domain::get()
{
  return generic_code_domain;
}
// Enable implicit construction of generic_code from errc
BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 inline generic_code make_status_code(errc c) noexcept
{
  return generic_code(in_place, c);
}

/*************************************************************************************************************/

template <class T> inline bool status_code<void>::equivalent(const status_code<T> &o) const noexcept
{
  if(_domain && o._domain)
  {
    if(_domain->_do_equivalent(*this, o))
    {
      return true;
    }
    if(o._domain->_do_equivalent(o, *this))
    {
      return true;
    }
    generic_code c1 = o._domain->_generic_code(o);
    if(c1.value() != errc::unknown && _domain->_do_equivalent(*this, c1))
    {
      return true;
    }
    generic_code c2 = _domain->_generic_code(*this);
    if(c2.value() != errc::unknown && o._domain->_do_equivalent(o, c2))
    {
      return true;
    }
  }
  // If we are both empty, we are equivalent, otherwise not equivalent
  return (!_domain && !o._domain);
}
//! True if the status code's are semantically equal via `equivalent()`.
template <class DomainType1, class DomainType2> inline bool operator==(const status_code<DomainType1> &a, const status_code<DomainType2> &b) noexcept
{
  return a.equivalent(b);
}
//! True if the status code's are not semantically equal via `equivalent()`.
template <class DomainType1, class DomainType2> inline bool operator!=(const status_code<DomainType1> &a, const status_code<DomainType2> &b) noexcept
{
  return !a.equivalent(b);
}
//! True if the status code's are semantically equal via `equivalent()` to `make_status_code(T)`.
template <class DomainType1, class T,                                                                       //
          class MakeStatusCodeResult = typename detail::safe_get_make_status_code_result<const T &>::type,  // Safe ADL lookup of make_status_code(), returns void if not found
          typename std::enable_if<is_status_code<MakeStatusCodeResult>::value, bool>::type = true>          // ADL makes a status code
inline bool
operator==(const status_code<DomainType1> &a, const T &b)
{
  return a.equivalent(make_status_code(b));
}
//! True if the status code's are semantically equal via `equivalent()` to `make_status_code(T)`.
template <class T, class DomainType1,                                                                       //
          class MakeStatusCodeResult = typename detail::safe_get_make_status_code_result<const T &>::type,  // Safe ADL lookup of make_status_code(), returns void if not found
          typename std::enable_if<is_status_code<MakeStatusCodeResult>::value, bool>::type = true>          // ADL makes a status code
inline bool
operator==(const T &a, const status_code<DomainType1> &b)
{
  return b.equivalent(make_status_code(a));
}
//! True if the status code's are not semantically equal via `equivalent()` to `make_status_code(T)`.
template <class DomainType1, class T,                                                                       //
          class MakeStatusCodeResult = typename detail::safe_get_make_status_code_result<const T &>::type,  // Safe ADL lookup of make_status_code(), returns void if not found
          typename std::enable_if<is_status_code<MakeStatusCodeResult>::value, bool>::type = true>          // ADL makes a status code
inline bool
operator!=(const status_code<DomainType1> &a, const T &b)
{
  return !a.equivalent(make_status_code(b));
}
//! True if the status code's are semantically equal via `equivalent()` to `make_status_code(T)`.
template <class T, class DomainType1,                                                                       //
          class MakeStatusCodeResult = typename detail::safe_get_make_status_code_result<const T &>::type,  // Safe ADL lookup of make_status_code(), returns void if not found
          typename std::enable_if<is_status_code<MakeStatusCodeResult>::value, bool>::type = true>          // ADL makes a status code
inline bool
operator!=(const T &a, const status_code<DomainType1> &b)
{
  return !b.equivalent(make_status_code(a));
}

BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_END

#endif


text:
## Azure AD Connect: PowerShell Commands to Configure Accidental Deletion Functionality (Prevent Accidental Deletes) ##

## Resource: http://blog.kloud.com.au/2015/08/05/azure-active-directory-connect-export-profile-error-stopped-server-down

## AAD Connect Commandlets: https://mikecrowley.wordpress.com/2015/10/11/azure-ad-connect-powershell-cmdlets

#Import the Azure AD Connect Sync module

Import-Module ADSync

#Disable / Enable ADSync export deletion threshold

Disable-ADSyncExportDeletionThreshold

#Enable-ADSyncExportDeletionThreshold

#Confirm the status of the 'ADSyncExportDeletionThreshold' property

Get-ADSyncExportDeletionThreshold


text:
<?php
namespace Concrete\Core\User\Workflow\Progress;

use Concrete\Core\User\UserInfo;
use Concrete\Core\Workflow\Progress\UserProgress;

class User
{

    public function __construct(UserInfo $u, UserProgress $wp)
    {
        $this->user = $u;
        $this->wp = $wp;
    }

    public function getUserObject()
    {
        return $this->user;
    }

    public function getWorkflowProgressObject()
    {
        return $this->wp;
    }
}


text:
class CreateCancelledOrderEvents < ActiveRecord::Migration
  def change
    create_table :cancelled_order_events do |t|
      t.integer :cancelled_by_id
      t.integer :customer_id
      t.text :order_details
      t.timestamps
    end
  end
end


text:
namespace PeinearyDevelopment.Framework.Filtering.Data.Entity
{
  using System.Collections.Generic;

  internal class DbObjectMapper
    {
        public string DbSchema { get; set; }
        public string DbTableName { get; set; }
        public IDictionary<string, string> ObjectPropertyColumnNameMapper { get; set; }
        public string PrimaryKeyPropertyName { get; set; }
    }
}


text:
'use strict';

const models = require('./index');

/**
 * Contains information about an Azure Batch account.
 *
 * @extends models['Resource']
 */
class BatchAccount extends models['Resource'] {
  /**
   * Create a BatchAccount.
   * @property {string} [accountEndpoint] The account endpoint used to interact
   * with the Batch service.
   * @property {string} [provisioningState] The provisioned state of the
   * resource. Possible values include: 'Invalid', 'Creating', 'Deleting',
   * 'Succeeded', 'Failed', 'Cancelled'
   * @property {string} [poolAllocationMode] The allocation mode to use for
   * creating pools in the Batch account. Possible values include:
   * 'BatchService', 'UserSubscription'
   * @property {object} [keyVaultReference] A reference to the Azure key vault
   * associated with the Batch account.
   * @property {string} [keyVaultReference.id] The resource ID of the Azure key
   * vault associated with the Batch account.
   * @property {string} [keyVaultReference.url] The URL of the Azure key vault
   * associated with the Batch account.
   * @property {string} [publicNetworkAccess] The network interface type for
   * accessing Azure Batch service and Batch account operations. If not
   * specified, the default value is 'enabled'. Possible values include:
   * 'Enabled', 'Disabled'. Default value: 'Enabled' .
   * @property {array} [privateEndpointConnections] List of private endpoint
   * connections associated with the Batch account
   * @property {object} [autoStorage] The properties and status of any
   * auto-storage account associated with the Batch account.
   * @property {date} [autoStorage.lastKeySync] The UTC time at which storage
   * keys were last synchronized with the Batch account.
   * @property {object} [encryption] The encryption configuration for the Batch
   * account. Configures how customer data is encrypted inside the Batch
   * account. By default, accounts are encrypted using a Microsoft managed key.
   * For additional control, a customer-managed key can be used instead.
   * @property {string} [encryption.keySource] Type of the key source. Possible
   * values include: 'Microsoft.Batch', 'Microsoft.KeyVault'
   * @property {object} [encryption.keyVaultProperties] Additional details when
   * using Microsoft.KeyVault
   * @property {string} [encryption.keyVaultProperties.keyIdentifier] Full path
   * to the versioned secret. Example
   * https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053.
   * To be usable the following prerequisites must be met:
   *
   * The Batch Account has a System Assigned identity
   * The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap
   * permissions
   * The KeyVault has soft-delete and purge protection enabled
   * @property {number} [dedicatedCoreQuota] The dedicated core quota for the
   * Batch account. For accounts with PoolAllocationMode set to
   * UserSubscription, quota is managed on the subscription so this value is
   * not returned.
   * @property {number} [lowPriorityCoreQuota] The low-priority core quota for
   * the Batch account. For accounts with PoolAllocationMode set to
   * UserSubscription, quota is managed on the subscription so this value is
   * not returned.
   * @property {array} [dedicatedCoreQuotaPerVMFamily] A list of the dedicated
   * core quota per Virtual Machine family for the Batch account. For accounts
   * with PoolAllocationMode set to UserSubscription, quota is managed on the
   * subscription so this value is not returned.
   * @property {boolean} [dedicatedCoreQuotaPerVMFamilyEnforced] A value
   * indicating whether the core quota for the Batch Account is enforced per
   * Virtual Machine family or not. Batch is transitioning its core quota
   * system for dedicated cores to be enforced per Virtual Machine family.
   * During this transitional phase, the dedicated core quota per Virtual
   * Machine family may not yet be enforced. If this flag is false, dedicated
   * core quota is enforced via the old dedicatedCoreQuota property on the
   * account and does not consider Virtual Machine family. If this flag is
   * true, dedicated core quota is enforced via the
   * dedicatedCoreQuotaPerVMFamily property on the account, and the old
   * dedicatedCoreQuota does not apply.
   * @property {number} [poolQuota] The pool quota for the Batch account.
   * @property {number} [activeJobAndJobScheduleQuota] The active job and job
   * schedule quota for the Batch account.
   * @property {object} [identity] The identity of the Batch account.
   * @property {string} [identity.principalId] The principal id of the Batch
   * account. This property will only be provided for a system assigned
   * identity.
   * @property {string} [identity.tenantId] The tenant id associated with the
   * Batch account. This property will only be provided for a system assigned
   * identity.
   * @property {string} [identity.type] The type of identity used for the Batch
   * account. Possible values include: 'SystemAssigned', 'None'
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of BatchAccount
   *
   * @returns {object} metadata of BatchAccount
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'BatchAccount',
      type: {
        name: 'Composite',
        className: 'BatchAccount',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: false,
            readOnly: true,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            readOnly: true,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          accountEndpoint: {
            required: false,
            readOnly: true,
            serializedName: 'properties.accountEndpoint',
            type: {
              name: 'String'
            }
          },
          provisioningState: {
            required: false,
            nullable: false,
            readOnly: true,
            serializedName: 'properties.provisioningState',
            type: {
              name: 'Enum',
              allowedValues: [ 'Invalid', 'Creating', 'Deleting', 'Succeeded', 'Failed', 'Cancelled' ]
            }
          },
          poolAllocationMode: {
            required: false,
            readOnly: true,
            serializedName: 'properties.poolAllocationMode',
            type: {
              name: 'Enum',
              allowedValues: [ 'BatchService', 'UserSubscription' ]
            }
          },
          keyVaultReference: {
            required: false,
            readOnly: true,
            serializedName: 'properties.keyVaultReference',
            type: {
              name: 'Composite',
              className: 'KeyVaultReference'
            }
          },
          publicNetworkAccess: {
            required: false,
            readOnly: true,
            serializedName: 'properties.publicNetworkAccess',
            defaultValue: 'Enabled',
            type: {
              name: 'Enum',
              allowedValues: [ 'Enabled', 'Disabled' ]
            }
          },
          privateEndpointConnections: {
            required: false,
            nullable: true,
            readOnly: true,
            serializedName: 'properties.privateEndpointConnections',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'PrivateEndpointConnectionElementType',
                  type: {
                    name: 'Composite',
                    className: 'PrivateEndpointConnection'
                  }
              }
            }
          },
          autoStorage: {
            required: false,
            readOnly: true,
            serializedName: 'properties.autoStorage',
            type: {
              name: 'Composite',
              className: 'AutoStorageProperties'
            }
          },
          encryption: {
            required: false,
            readOnly: true,
            serializedName: 'properties.encryption',
            type: {
              name: 'Composite',
              className: 'EncryptionProperties'
            }
          },
          dedicatedCoreQuota: {
            required: false,
            nullable: true,
            readOnly: true,
            serializedName: 'properties.dedicatedCoreQuota',
            type: {
              name: 'Number'
            }
          },
          lowPriorityCoreQuota: {
            required: false,
            nullable: true,
            readOnly: true,
            serializedName: 'properties.lowPriorityCoreQuota',
            type: {
              name: 'Number'
            }
          },
          dedicatedCoreQuotaPerVMFamily: {
            required: false,
            nullable: true,
            readOnly: true,
            serializedName: 'properties.dedicatedCoreQuotaPerVMFamily',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'VirtualMachineFamilyCoreQuotaElementType',
                  type: {
                    name: 'Composite',
                    className: 'VirtualMachineFamilyCoreQuota'
                  }
              }
            }
          },
          dedicatedCoreQuotaPerVMFamilyEnforced: {
            required: false,
            nullable: false,
            readOnly: true,
            serializedName: 'properties.dedicatedCoreQuotaPerVMFamilyEnforced',
            type: {
              name: 'Boolean'
            }
          },
          poolQuota: {
            required: false,
            nullable: false,
            readOnly: true,
            serializedName: 'properties.poolQuota',
            type: {
              name: 'Number'
            }
          },
          activeJobAndJobScheduleQuota: {
            required: false,
            nullable: false,
            readOnly: true,
            serializedName: 'properties.activeJobAndJobScheduleQuota',
            type: {
              name: 'Number'
            }
          },
          identity: {
            required: false,
            serializedName: 'identity',
            type: {
              name: 'Composite',
              className: 'BatchAccountIdentity'
            }
          }
        }
      }
    };
  }
}

module.exports = BatchAccount;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.jeo</groupId>
    <artifactId>contrib</artifactId>
    <version>0-SNAPSHOT</version>
  </parent>

  <artifactId>jeo-lucene</artifactId>
  <name>Lucene Driver</name>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>io.jeo</groupId>
      <artifactId>jeo</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-analyzers-common</artifactId>
      <version>${lucene.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-spatial</artifactId>
      <version>${lucene.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-queryparser</artifactId>
      <version>${lucene.version}</version>
    </dependency>
    <dependency>
      <groupId>io.jeo</groupId>
      <artifactId>jeo</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
      <classifier>tests</classifier>
    </dependency>
  </dependencies>

  <properties>
    <lucene.version>5.0.0</lucene.version>
  </properties>
</project>


text:
import os
from base64 import b64encode
from urllib.parse import quote

def g_b64(data):
    return b"".join([b"data:image/svg+xml;base64,", b64encode(data.encode("utf-8"))])

def g_uri(data):
    return "".join(["data:image/svg+xml;charset=UTF-8,", quote(data)])

def svg_to_data(data):
    d_b64 = g_b64(data)
    d_uri = g_uri(data)
    if len(d_b64) > len(d_uri):
        return d_uri
    return d_b64

def svg_to_data_uri(file_path, include_paths):
    for path in include_paths:
        try:
            with open(os.path.join(path, file_path)) as f:
                return svg_to_data(f.read())
        except FileNotFoundError:
            pass
    raise FileNotFoundError(file_path)


text:
#ifndef _M_EVAL_H
#define _M_EVAL_H

#include "main/glheader.h"

void _math_init_eval( void );

/*
 * Horner scheme for Bezier curves
 *
 * Bezier curves can be computed via a Horner scheme.
 * Horner is numerically less stable than the de Casteljau
 * algorithm, but it is faster. For curves of degree n
 * the complexity of Horner is O(n) and de Casteljau is O(n^2).
 * Since stability is not important for displaying curve
 * points I decided to use the Horner scheme.
 *
 * A cubic Bezier curve with control points b0, b1, b2, b3 can be
 * written as
 *
 *        (([3]        [3]     )     [3]       )     [3]
 * c(t) = (([0]*s*b0 + [1]*t*b1)*s + [2]*t^2*b2)*s + [3]*t^2*b3
 *
 *                                           [n]
 * where s=1-t and the binomial coefficients [i]. These can
 * be computed iteratively using the identity:
 *
 * [n]               [n  ]             [n]
 * [i] = (n-i+1)/i * [i-1]     and     [0] = 1
 */

void
_math_horner_bezier_curve(const GLfloat *cp, GLfloat *out, GLfloat t,
			  GLuint dim, GLuint order);

/*
 * Tensor product Bezier surfaces
 *
 * Again the Horner scheme is used to compute a point on a
 * TP Bezier surface. First a control polygon for a curve
 * on the surface in one parameter direction is computed,
 * then the point on the curve for the other parameter
 * direction is evaluated.
 *
 * To store the curve control polygon additional storage
 * for max(uorder,vorder) points is needed in the
 * control net cn.
 */

void
_math_horner_bezier_surf(GLfloat *cn, GLfloat *out, GLfloat u, GLfloat v,
			 GLuint dim, GLuint uorder, GLuint vorder);

/*
 * The direct de Casteljau algorithm is used when a point on the
 * surface and the tangent directions spanning the tangent plane
 * should be computed (this is needed to compute normals to the
 * surface). In this case the de Casteljau algorithm approach is
 * nicer because a point and the partial derivatives can be computed
 * at the same time. To get the correct tangent length du and dv
 * must be multiplied with the (u2-u1)/uorder-1 and (v2-v1)/vorder-1.
 * Since only the directions are needed, this scaling step is omitted.
 *
 * De Casteljau needs additional storage for uorder*vorder
 * values in the control net cn.
 */

void
_math_de_casteljau_surf(GLfloat *cn, GLfloat *out, GLfloat *du, GLfloat *dv,
			GLfloat u, GLfloat v, GLuint dim,
			GLuint uorder, GLuint vorder);

#endif


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('widgetbox', '0019_tab_tabpane'),
    ]

    operations = [
        migrations.AlterField(
            model_name='tabpane',
            name='tabid',
            field=models.SlugField(max_length=200, blank=True),
        ),
    ]


text:
package org.jboss.pnc.restclient.websocket.predicates;

import java.util.function.Predicate;

import org.jboss.pnc.dto.notification.BuildChangedNotification;
import org.jboss.pnc.enums.BuildStatus;

public final class BuildChangedNotificationPredicates {

    private BuildChangedNotificationPredicates() {
    }

    public static Predicate<BuildChangedNotification> withBuildId(String buildId) {
        return (notification) -> notification.getBuild().getId().equals(buildId);
    }

    public static Predicate<BuildChangedNotification> withBuildStatus(BuildStatus status) {
        return (notification) -> notification.getBuild().getStatus().equals(status);
    }

    public static Predicate<BuildChangedNotification> isSuccessful() {
        return (notification) -> notification.getBuild().getStatus().completedSuccessfully();
    }

    public static Predicate<BuildChangedNotification> withBuildCompleted() {
        return (notification) -> notification.getBuild().getStatus().isFinal();
    }

    public static Predicate<BuildChangedNotification> withBuildConfiguration(String buildConfigId) {
        return (notification) -> notification.getBuild().getBuildConfigRevision().getId().equals(buildConfigId);
    }
}