text:
package main

import (
	"fmt"
	"net"
	"strconv"

	"github.com/pkg/errors"

	"github.com/cloudflare/cloudflare-go"
	"github.com/codegangsta/cli"
)

func formatAccessRule(rule cloudflare.AccessRule) []string {
	return []string{
		rule.ID,
		rule.Configuration.Value,
		rule.Scope.Type,
		rule.Mode,
		rule.Notes,
	}
}

func firewallAccessRules(c *cli.Context) {
	if err := checkEnv(); err != nil {
		fmt.Println(err)
		return
	}

	organizationID, zoneID, err := getScope(c)
	if err != nil {
		return
	}

	// Create an empty access rule for searching for rules
	rule := cloudflare.AccessRule{
		Configuration: getConfiguration(c),
	}
	if c.String("scope-type") != "" {
		rule.Scope.Type = c.String("scope-type")
	}
	if c.String("notes") != "" {
		rule.Notes = c.String("notes")
	}
	if c.String("mode") != "" {
		rule.Mode = c.String("mode")
	}

	var response *cloudflare.AccessRuleListResponse
	switch {
	case organizationID != "":
		response, err = api.ListOrganizationAccessRules(organizationID, rule, 1)
	case zoneID != "":
		response, err = api.ListZoneAccessRules(zoneID, rule, 1)
	default:
		response, err = api.ListUserAccessRules(rule, 1)
	}
	if err != nil {
		fmt.Println(err)
		return
	}
	totalPages := response.ResultInfo.TotalPages
	rules := make([]cloudflare.AccessRule, 0, response.ResultInfo.Total)
	rules = append(rules, response.Result...)
	if totalPages > 1 {
		for page := 2; page < totalPages; page++ {
			switch {
			case organizationID != "":
				response, err = api.ListOrganizationAccessRules(organizationID, rule, page)
			case zoneID != "":
				response, err = api.ListZoneAccessRules(zoneID, rule, page)
			default:
				response, err = api.ListUserAccessRules(rule, page)
			}
			if err != nil {
				fmt.Println(err)
				return
			}
			rules = append(rules, response.Result...)
		}
	}

	output := make([][]string, 0, len(rules))
	for _, rule := range rules {
		output = append(output, formatAccessRule(rule))
	}
	writeTable(output, "ID", "Value", "Scope", "Mode", "Notes")
}

func firewallAccessRuleCreate(c *cli.Context) {
	if err := checkEnv(); err != nil {
		fmt.Println(err)
		return
	}
	if err := checkFlags(c, "mode", "value"); err != nil {
		fmt.Println(err)
		return
	}
	organizationID, zoneID, err := getScope(c)
	if err != nil {
		return
	}
	configuration := getConfiguration(c)
	mode := c.String("mode")
	notes := c.String("notes")

	rule := cloudflare.AccessRule{
		Configuration: configuration,
		Mode:          mode,
		Notes:         notes,
	}

	var (
		rules       []cloudflare.AccessRule
		errCreating = "error creating firewall access rule"
	)

	switch {
	case organizationID != "":
		resp, err := api.CreateOrganizationAccessRule(organizationID, rule)
		if err != nil {
			errors.Wrap(err, errCreating)
		}
		rules = append(rules, resp.Result)
	case zoneID != "":
		resp, err := api.CreateZoneAccessRule(zoneID, rule)
		if err != nil {
			errors.Wrap(err, errCreating)
		}
		rules = append(rules, resp.Result)
	default:
		resp, err := api.CreateUserAccessRule(rule)
		if err != nil {
			errors.Wrap(err, errCreating)
		}
		rules = append(rules, resp.Result)

	}

	output := make([][]string, 0, len(rules))
	for _, rule := range rules {
		output = append(output, formatAccessRule(rule))
	}
	writeTable(output, "ID", "Value", "Scope", "Mode", "Notes")
}

func firewallAccessRuleUpdate(c *cli.Context) {
	if err := checkEnv(); err != nil {
		fmt.Println(err)
		return
	}
	if err := checkFlags(c, "id"); err != nil {
		fmt.Println(err)
		return
	}
	id := c.String("id")
	organizationID, zoneID, err := getScope(c)
	if err != nil {
		return
	}
	mode := c.String("mode")
	notes := c.String("notes")

	rule := cloudflare.AccessRule{
		Mode:  mode,
		Notes: notes,
	}

	var (
		rules       []cloudflare.AccessRule
		errUpdating = "error updating firewall access rule"
	)
	switch {
	case organizationID != "":
		resp, err := api.UpdateOrganizationAccessRule(organizationID, id, rule)
		if err != nil {
			errors.Wrap(err, errUpdating)
		}
		rules = append(rules, resp.Result)
	case zoneID != "":
		resp, err := api.UpdateZoneAccessRule(zoneID, id, rule)
		if err != nil {
			errors.Wrap(err, errUpdating)
		}
		rules = append(rules, resp.Result)
	default:
		resp, err := api.UpdateUserAccessRule(id, rule)
		if err != nil {
			errors.Wrap(err, errUpdating)
		}
		rules = append(rules, resp.Result)
	}

	output := make([][]string, 0, len(rules))
	for _, rule := range rules {
		output = append(output, formatAccessRule(rule))
	}
	writeTable(output, "ID", "Value", "Scope", "Mode", "Notes")

}

func firewallAccessRuleCreateOrUpdate(c *cli.Context) {
	if err := checkEnv(); err != nil {
		fmt.Println(err)
		return
	}
	if err := checkFlags(c, "mode", "value"); err != nil {
		fmt.Println(err)
		return
	}
	organizationID, zoneID, err := getScope(c)
	if err != nil {
		return
	}
	configuration := getConfiguration(c)
	mode := c.String("mode")
	notes := c.String("notes")

	// Look for an existing record
	rule := cloudflare.AccessRule{
		Configuration: configuration,
	}
	var response *cloudflare.AccessRuleListResponse
	switch {
	case organizationID != "":
		response, err = api.ListOrganizationAccessRules(organizationID, rule, 1)
	case zoneID != "":
		response, err = api.ListZoneAccessRules(zoneID, rule, 1)
	default:
		response, err = api.ListUserAccessRules(rule, 1)
	}
	if err != nil {
		fmt.Println("Error creating or updating firewall access rule:", err)
		return
	}

	rule.Mode = mode
	rule.Notes = notes
	if len(response.Result) > 0 {
		for _, r := range response.Result {
			if mode == "" {
				rule.Mode = r.Mode
			}
			if notes == "" {
				rule.Notes = r.Notes
			}
			switch {
			case organizationID != "":
				_, err = api.UpdateOrganizationAccessRule(organizationID, r.ID, rule)
			case zoneID != "":
				_, err = api.UpdateZoneAccessRule(zoneID, r.ID, rule)
			default:
				_, err = api.UpdateUserAccessRule(r.ID, rule)
			}
			if err != nil {
				fmt.Println("Error updating firewall access rule:", err)
			}
		}
	} else {
		switch {
		case organizationID != "":
			_, err = api.CreateOrganizationAccessRule(organizationID, rule)
		case zoneID != "":
			_, err = api.CreateZoneAccessRule(zoneID, rule)
		default:
			_, err = api.CreateUserAccessRule(rule)
		}
		if err != nil {
			fmt.Println("Error creating firewall access rule:", err)
		}
	}
}

func firewallAccessRuleDelete(c *cli.Context) {
	if err := checkEnv(); err != nil {
		fmt.Println(err)
		return
	}
	if err := checkFlags(c, "id"); err != nil {
		fmt.Println(err)
		return
	}
	ruleID := c.String("id")

	organizationID, zoneID, err := getScope(c)
	if err != nil {
		return
	}

	var (
		rules       []cloudflare.AccessRule
		errDeleting = "error deleting firewall access rule"
	)
	switch {
	case organizationID != "":
		resp, err := api.DeleteOrganizationAccessRule(organizationID, ruleID)
		if err != nil {
			errors.Wrap(err, errDeleting)
		}
		rules = append(rules, resp.Result)
	case zoneID != "":
		resp, err := api.DeleteZoneAccessRule(zoneID, ruleID)
		if err != nil {
			errors.Wrap(err, errDeleting)
		}
		rules = append(rules, resp.Result)
	default:
		resp, err := api.DeleteUserAccessRule(ruleID)
		if err != nil {
			errors.Wrap(err, errDeleting)
		}
		rules = append(rules, resp.Result)
	}
	if err != nil {
		fmt.Println("Error deleting firewall access rule:", err)
	}
}

func getScope(c *cli.Context) (string, string, error) {
	var organization, organizationID string
	if c.String("organization") != "" {
		organization = c.String("organization")
		organizations, _, err := api.ListOrganizations()
		if err != nil {
			fmt.Println(err)
			return "", "", err
		}
		for _, org := range organizations {
			if org.Name == organization {
				organizationID = org.ID
				break
			}
		}
		if organizationID == "" {
			err := errors.New("Organization could not be found")
			fmt.Println(err)
			return "", "", err
		}
	}

	var zone, zoneID string
	if c.String("zone") != "" {
		zone = c.String("zone")
		id, err := api.ZoneIDByName(zone)
		if err != nil {
			fmt.Println(err)
			return "", "", err
		}
		zoneID = id
	}

	if zoneID != "" && organizationID != "" {
		err := errors.New("Cannot specify both --zone and --organization")
		fmt.Println(err)
		return "", "", err
	}

	return organizationID, zoneID, nil
}

func getConfiguration(c *cli.Context) cloudflare.AccessRuleConfiguration {
	configuration := cloudflare.AccessRuleConfiguration{}
	if c.String("value") != "" {
		ip := net.ParseIP(c.String("value"))
		_, cidr, cidrErr := net.ParseCIDR(c.String("value"))
		_, asnErr := strconv.ParseInt(c.String("value"), 10, 32)
		if ip != nil {
			configuration.Target = "ip"
			configuration.Value = ip.String()
		} else if cidrErr == nil {
			cidr.IP = cidr.IP.Mask(cidr.Mask)
			configuration.Target = "ip_range"
			configuration.Value = cidr.String()
		} else if asnErr == nil {
			configuration.Target = "asn"
			configuration.Value = c.String("value")
		} else {
			configuration.Target = "country"
			configuration.Value = c.String("value")
		}
	}
	return configuration
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>IOSS: Iocgns::ZoneData Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

IOSS
    2.0

Public Attributes |
List of all members

Iocgns::ZoneData Class Reference

#include <Iocgns_DecompositionData.h>

Public Attributes

std::string 	m_name

size_t 	m_nodeOffset

size_t 	m_nodeCount

size_t 	m_elementOffset

Member Data Documentation

◆ m_elementOffset

          size_t Iocgns::ZoneData::m_elementOffset

◆ m_name

          std::string Iocgns::ZoneData::m_name

◆ m_nodeCount

          size_t Iocgns::ZoneData::m_nodeCount

◆ m_nodeOffset

          size_t Iocgns::ZoneData::m_nodeOffset

The documentation for this class was generated from the following file:

src/cgns/Iocgns_DecompositionData.h

Iocgns

ZoneData

Generated by

     1.8.13

redpajama_set_name: RedPajamaGithub


text:
default['selenium']['IEDriver']['directory'] = 'C:\selenium'
case node["kernel"]["machine"]
when "x86_64"
  default["selenium"]["IEDriver"]["url"] = "https://selenium.googlecode.com/files/IEDriverServer_x64_2.32.3.zip"
else
  default["selenium"]["IEDriver"]["url"] = "https://selenium.googlecode.com/files/IEDriverServer_Win32_2.32.3.zip"
end


text:
import numpy as np
from functools import partial
from itertools import izip
from tqdm import tqdm
from scipy.sparse import coo_matrix
from pymaptools.containers import DefaultOrderedDict
from collections import defaultdict

def dd2coo(dd, dtype=np.float32):
    """
    Convert a dict of dicts to COO-type sparse matrix
    """
    # first create maps from key values to rows and columns

    # first level
    row_list = dd.keys()
    col_list = list(set(k for row in dd.itervalues() for k in row.iterkeys()))
    row_map = {k: idx for idx, k in enumerate(row_list)}
    col_map = {k: idx for idx, k in enumerate(col_list)}

    values = []
    row_indices = []
    col_indices = []
    for row_key, row in dd.iteritems():
        row_idx = row_map[row_key]
        for col_key, val in row.iteritems():
            values.append(val)
            row_indices.append(row_idx)
            col_indices.append(col_map[col_key])

    return row_list, col_list, coo_matrix((values, (row_indices, col_indices)), dtype=dtype)

def csr2dd(mat, transpose=False, show_progress=False):
    """Convert a CSR sparse matrix to dict-of-dicts format
    """
    dd = defaultdict(partial(dict))
    for i, j, v in iter_csr(mat, transpose=transpose, show_progress=show_progress):
        dd[i][j] = v
    return dd

class CooBuilder(object):

    """A simple demonstration of dd2coo usage
    """
    def __init__(self, dtype):

        self._dtype = dtype
        self._dict = DefaultOrderedDict(partial(DefaultOrderedDict, dtype))

    def add(self, x, y, val):

        self._dict[x][y] += val

    def assign(self, x, y, val):

        self._dict[x][y] = val

    def get_coo(self, transpose=False):

        rows, cols, mat = dd2coo(self._dict, dtype=self._dtype)
        if transpose:
            return cols, rows, mat.T
        else:
            return rows, cols, mat

def iter_csr(mat, transpose=False, show_progress=False):
    """Iterate over CSR matrix in memory-efficient way
    """
    indices = mat.nonzero()
    data = mat.data
    assert indices[0].shape[0] == indices[1].shape[0] == data.shape[0]
    li, ri = (1, 0) if transpose else (0, 1)
    iterator = izip(indices[li], indices[ri], data)
    if show_progress:
        iterator = tqdm(iterator, total=mat.nnz)
    return iterator


text:
module BackerStateMachineHandler
  extend ActiveSupport::Concern

  included do
    state_machine :state, initial: :pending do
      state :pending, value: 'pending'
      state :waiting_confirmation, value: 'waiting_confirmation'
      state :confirmed, value: 'confirmed'
      state :canceled, value: 'canceled'
      state :refunded, value: 'refunded'
      state :requested_refund, value: 'requested_refund'
      state :refunded_and_canceled, value: 'refunded_and_canceled'
      state :deleted, value: 'deleted'

      event :push_to_trash do
        transition all => :deleted
      end

      event :pendent do
        transition all => :pending
      end

      event :waiting do
        transition pending: :waiting_confirmation
      end

      event :confirm do
        transition all => :confirmed
      end

      event :cancel do
        transition all => :canceled
      end

      event :request_refund do
        transition confirmed: :requested_refund, if: ->(backer){
          backer.user.credits >= backer.value && !backer.credits
        }
      end

      event :refund do
        transition [:requested_refund, :confirmed] => :refunded
      end

      event :hide do
        transition all => :refunded_and_canceled
      end

      after_transition confirmed: :requested_refund, do: :after_transition_from_confirmed_to_requested_refund

      after_transition confirmed: :canceled, do: :after_transition_from_confirmed_to_canceled

      after_transition do |backer, transition|
        backer.notify_observers :"from_#{transition.from}_to_#{transition.to}"
      end

    end

    def after_transition_from_confirmed_to_canceled
      notify_observers :notify_backoffice_about_canceled
    end

    def after_transition_from_confirmed_to_requested_refund
      notify_observers :notify_backoffice
    end
  end
end


text:
from binder.conn import Connection, READ_COMMITTED, REPEATABLE_READ, \
    _VALID_ISOLATION_LEVELS
from binder.sqlgen import DIALECT_POSTGRES

_psycopg2_imported = False
_ISOLATION_LEVEL_MAP = {}

def _import_psycopg2():
    global _psycopg2_imported, psycopg2, _ISOLATION_LEVEL_MAP
    #
    if _psycopg2_imported:
        return
    #
    import psycopg2
    _psycopg2_imported = True
    #
    from psycopg2 import extensions
    #
    psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
    psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
    #
    _ISOLATION_LEVEL_MAP.update({
        #ISOLATION_LEVEL_AUTOCOMMIT
        #ISOLATION_LEVEL_READ_UNCOMMITTED
        READ_COMMITTED: extensions.ISOLATION_LEVEL_READ_COMMITTED,
        REPEATABLE_READ: extensions.ISOLATION_LEVEL_REPEATABLE_READ,
        #ISOLATION_LEVEL_SERIALIZABLE
        })

class PostgresConnection(Connection):

    def __init__(self, *args, **kwargs):
        _import_psycopg2()
        read_only = kwargs.pop('read_only', None)
        isolation_level = kwargs.pop('isolation_level', REPEATABLE_READ)
        assert isolation_level in _VALID_ISOLATION_LEVELS, \
            ("Unknown isolation_level", isolation_level)
        #
        pg_isolation_level = _ISOLATION_LEVEL_MAP[isolation_level]
        #
        dbconn = psycopg2.connect(*args, **kwargs)
        dbconn.set_session(pg_isolation_level)
        dberror = psycopg2.Error
        Connection.__init__(
            self, dbconn, dberror,
            DIALECT_POSTGRES, "%s",
            read_only
            )


text:
'use strict';

require('./consoles-list.module.js');

angular
    .module('consolesList')
    .component('consolesList', {
        templateUrl: 'components/consoles-list/consoles-list.template.html',
        controller: ["$http", "$scope", 'appService', function ConsolesListController($http, $scope, appService) {
            var controller = this;
            $scope.controller = controller;
            controller.orderProperty = 'name';
            controller.appService = appService;

            appService.getData('./../../dist/json/consoles/consoles.json', 'consoles').then(function(response) {
                controller.consoles = response;
            }, function() {
                console.log('promise failed');
            });

            controller.AddConsole = function (age, name, imageUrl, description) {
                controller.consoles.push({
                    age: age,
                    name: name,
                    imageUrl: imageUrl,
                    description: description
                })
            };
        }]
    });


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "default", {
  enumerable: true,
  get: function get() {
    return _uxcoreTimePicker.default;
  }
});

var _uxcoreTimePicker = _interopRequireDefault(require("uxcore-time-picker"));

module.exports = exports.default;


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

<TITLE>
LimitHandler (Hibernate JavaDocs)
</TITLE>

<META NAME="date" CONTENT="2013-10-23">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.hibernate.dialect.pagination

Interface LimitHandler

All Known Implementing Classes:
AbstractLimitHandler, LegacyLimitHandler, NoopLimitHandler, SQLServer2005LimitHandler

public interface LimitHandler

Contract defining dialect-specific LIMIT clause handling. Typically implementers might consider extending
 AbstractLimitHandler class.

Method Summary

 int
bindLimitParametersAtEndOfQuery(PreparedStatement statement,
                                int index)

          Bind parameter values needed by the LIMIT clause after original SELECT statement.

 int
bindLimitParametersAtStartOfQuery(PreparedStatement statement,
                                  int index)

          Bind parameter values needed by the LIMIT clause before original SELECT statement.

 String
getProcessedSql()

          Return processed SQL query.

 void
setMaxRows(PreparedStatement statement)

          Use JDBC API to limit the number of rows returned by the SQL query.

 boolean
supportsLimit()

          Does this handler support some form of limiting query results
 via a SQL clause?

 boolean
supportsLimitOffset()

          Does this handler's LIMIT support (if any) additionally
 support specifying an offset?

Method Detail

supportsLimit

boolean supportsLimit()

Does this handler support some form of limiting query results
 via a SQL clause?

Returns:
True if this handler supports some form of LIMIT.

supportsLimitOffset

boolean supportsLimitOffset()

Does this handler's LIMIT support (if any) additionally
 support specifying an offset?

Returns:
True if the handler supports an offset within the limit support.

getProcessedSql

String getProcessedSql()

Return processed SQL query.

Returns:
Query statement with LIMIT clause applied.

bindLimitParametersAtStartOfQuery

int bindLimitParametersAtStartOfQuery(PreparedStatement statement,
                                      int index)
                                      throws SQLException

Bind parameter values needed by the LIMIT clause before original SELECT statement.

Parameters:
statement - Statement to which to bind limit parameter values.
index - Index from which to start binding.

Returns:
The number of parameter values bound.

Throws:

SQLException - Indicates problems binding parameter values.

bindLimitParametersAtEndOfQuery

int bindLimitParametersAtEndOfQuery(PreparedStatement statement,
                                    int index)
                                    throws SQLException

Bind parameter values needed by the LIMIT clause after original SELECT statement.

Parameters:
statement - Statement to which to bind limit parameter values.
index - Index from which to start binding.

Returns:
The number of parameter values bound.

Throws:

SQLException - Indicates problems binding parameter values.

setMaxRows

void setMaxRows(PreparedStatement statement)
                throws SQLException

Use JDBC API to limit the number of rows returned by the SQL query. Typically handlers that do not
 support LIMIT clause should implement this method.

Parameters:
statement - Statement which number of returned rows shall be limited.

Throws:

SQLException - Indicates problems while limiting maximum rows returned.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2001-2013 Red Hat, Inc.  All Rights Reserved.


text:
package org.deeplearning4j.nn.conf.serde;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.config.DL4JSystemProperties;
import org.deeplearning4j.nn.conf.ComputationGraphConfiguration;
import org.deeplearning4j.nn.conf.InputPreProcessor;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.graph.GraphVertex;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.deeplearning4j.nn.conf.layers.variational.ReconstructionDistribution;
import org.deeplearning4j.nn.conf.serde.legacy.LegacyJsonFormat;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.serde.json.LegacyIActivationDeserializer;
import org.nd4j.serde.json.LegacyILossFunctionDeserializer;
import org.nd4j.shade.jackson.annotation.JsonTypeInfo;
import org.nd4j.shade.jackson.databind.*;
import org.nd4j.shade.jackson.databind.cfg.MapperConfig;
import org.nd4j.shade.jackson.databind.deser.BeanDeserializerModifier;
import org.nd4j.shade.jackson.databind.introspect.Annotated;
import org.nd4j.shade.jackson.databind.introspect.AnnotatedClass;
import org.nd4j.shade.jackson.databind.introspect.AnnotationMap;
import org.nd4j.shade.jackson.databind.introspect.JacksonAnnotationIntrospector;
import org.nd4j.shade.jackson.databind.jsontype.TypeResolverBuilder;
import org.nd4j.shade.jackson.databind.module.SimpleModule;
import org.nd4j.shade.jackson.dataformat.yaml.YAMLFactory;
import org.nd4j.util.OneTimeLogger;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * JSON mappers for deserializing neural net configurations, etc.
 *
 * @author Alex Black
 */
@Slf4j
public class JsonMappers {

    private static ObjectMapper jsonMapper = new ObjectMapper();
    private static ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());

    private static ObjectMapper legacyMapper;

    static {
        configureMapper(jsonMapper);
        configureMapper(yamlMapper);
    }

    /**
     * @return The default/primary ObjectMapper for deserializing JSON network configurations in DL4J
     */
    public static ObjectMapper getMapper(){
        return jsonMapper;
    }

    public static synchronized ObjectMapper getLegacyMapper(){
        if(legacyMapper == null){
            legacyMapper = LegacyJsonFormat.getMapper100alpha();
            configureMapper(legacyMapper);
        }
        return legacyMapper;
    }

    /**
     * @return The default/primary ObjectMapper for deserializing network configurations in DL4J (YAML format)
     */
    public static ObjectMapper getMapperYaml() {
        return yamlMapper;
    }

    private static void configureMapper(ObjectMapper ret) {
        ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        ret.enable(SerializationFeature.INDENT_OUTPUT);

        SimpleModule customDeserializerModule = new SimpleModule();
        customDeserializerModule.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                //Use our custom deserializers to handle backward compatibility for updaters -> IUpdater
                if (beanDesc.getBeanClass() == MultiLayerConfiguration.class) {
                    return new MultiLayerConfigurationDeserializer(deserializer);
                } else if (beanDesc.getBeanClass() == ComputationGraphConfiguration.class) {
                    return new ComputationGraphConfigurationDeserializer(deserializer);
                }
                return deserializer;
            }
        });

        ret.registerModule(customDeserializerModule);
    }
}


text:
<?php

namespace Akeeba\Engine\Postproc\Connector\S3v4\Exception;

// Protection against direct access
defined('AKEEBAENGINE') || die();

use Exception;

/**
 * Invalid Amazon S3 endpoint
 */
class InvalidEndpoint extends ConfigurationError
{
	public function __construct(string $message = "", int $code = 0, Exception $previous = null)
	{
		if (empty($message))
		{
			$message = 'The custom S3 endpoint provided is invalid. Do NOT include the protocol (http:// or https://). Valid examples are s3.example.com and www.example.com/s3Api';
		}

		parent::__construct($message, $code, $previous);
	}

}


text:
#ifndef __AP_HAL_EMPTY_GPIO_H__
#define __AP_HAL_EMPTY_GPIO_H__

#include <AP_HAL_Empty.h>

class Empty::EmptyGPIO : public AP_HAL::GPIO {
public:
    EmptyGPIO();
    void    init();
    void    pinMode(uint8_t pin, uint8_t output);
    int8_t  analogPinToDigitalPin(uint8_t pin);
    uint8_t read(uint8_t pin);
    void    write(uint8_t pin, uint8_t value);
    void    toggle(uint8_t pin);

    /* Alternative interface: */
    AP_HAL::DigitalSource* channel(uint16_t n);

    /* Interrupt interface: */
    bool    attach_interrupt(uint8_t interrupt_num, AP_HAL::Proc p,
            uint8_t mode);

    /* return true if USB cable is connected */
    bool    usb_connected(void);
};

class Empty::EmptyDigitalSource : public AP_HAL::DigitalSource {
public:
    EmptyDigitalSource(uint8_t v);
    void    mode(uint8_t output);
    uint8_t read();
    void    write(uint8_t value);
    void    toggle();
private:
    uint8_t _v;
};

#endif // __AP_HAL_EMPTY_GPIO_H__


text:
import { firstLists } from './firstState';

const list = (state, action) => {
  switch (action.type) {
    case 'CREATE_LIST':
      return {
        title: action.title,
        edit: false,
        editTitle: false
      };

    case 'TOGGLE_EDIT_LIST':
      if (state.title === action.title && action.title !== 'All') {
        return {
          ...state,
          edit: !state.edit
        };
      } else {
        return {
          ...state,
          edit: false
        };
      }
    case 'TOGGLE_LIST_TITLE':
      if (state.title === action.title) {
        return {
          ...state,
          editTitle: !state.editTitle
        };
      }
    case 'SUBMIT_EDIT_LIST':
      if (state.title === action.oldTitle) {
        return {
          ...state,
          title: action.newTitle
        };
      }
    default:
      return state;
  }
};
const lists = (state = firstLists, action) => {
  switch (action.type) {
    case 'CREATE_LIST':
      if (!state.find(s => s.title === action.title)) {
        if (action.title) {
          return [...state, list(undefined, action)];
        } else return state;
      } else return state;
    case 'TOGGLE_EDIT_LIST':
      return state.map(l => list(l, action));
    case 'TOGGLE_LIST_TITLE':
      return state.map(l => list(l, action));
    case 'DELETE_LIST':
      return state.filter(s => s.title !== action.title);
    case 'SUBMIT_EDIT_LIST':
      if (!state.find(s => s.title === action.newTitle)) {
        return state.map(l => list(l, action));
      } else return state;
    default:
      return state;
  }
};
export default lists;


text:
package io.aos.netty3.framing;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class LogServerHandler extends SimpleChannelHandler {

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        ChannelBuffer buf = (ChannelBuffer) e.getMessage();
		System.out.println("LogServer Received: " + buf.readableBytes());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		Channel ch = e.getChannel();
		ch.close();
	}
}


text:
extern const struct luaL_Reg CvSparseNode_m[];
#endif


text:
/*
 * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
 *
 * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or  other piece of equipment they want to hire out to the transportation ministry for day labour and  emergency projects.  The Hired Equipment Program distributes available work to local equipment owners. The program is  based on seniority and is designed to deliver work to registered users fairly and efficiently  through the development of local area call-out lists.
 *
 * OpenAPI spec version: v1
 *
 *
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using HETSAPI;
using HETSAPI.Models;
using System.Reflection;

namespace HETSAPI.Test
{
    /// <summary>
    ///  Class for testing the model UserDetailsViewModel
    /// </summary>

    public class UserDetailsViewModelModelTests
    {
        // TODO uncomment below to declare an instance variable for UserDetailsViewModel
        private UserDetailsViewModel instance;

        /// <summary>
        /// Setup the test.
        /// </summary>
        public UserDetailsViewModelModelTests()
        {
            instance = new UserDetailsViewModel();
        }

        /// <summary>
        /// Test an instance of UserDetailsViewModel
        /// </summary>
        [Fact]
        public void UserDetailsViewModelInstanceTest()
        {
            Assert.IsType<UserDetailsViewModel>(instance);
        }

        /// <summary>
        /// Test the property 'Id'
        /// </summary>
        [Fact]
        public void IdTest()
        {
            // TODO unit test for the property 'Id'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'Active'
        /// </summary>
        [Fact]
        public void ActiveTest()
        {
            // TODO unit test for the property 'Active'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'GivenName'
        /// </summary>
        [Fact]
        public void GivenNameTest()
        {
            // TODO unit test for the property 'GivenName'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'Surname'
        /// </summary>
        [Fact]
        public void SurnameTest()
        {
            // TODO unit test for the property 'Surname'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'Initials'
        /// </summary>
        [Fact]
        public void InitialsTest()
        {
            // TODO unit test for the property 'Initials'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'Email'
        /// </summary>
        [Fact]
        public void EmailTest()
        {
            // TODO unit test for the property 'Email'
			Assert.True(true);
        }
        /// <summary>
        /// Test the property 'Permissions'
        /// </summary>
        [Fact]
        public void PermissionsTest()
        {
            // TODO unit test for the property 'Permissions'
			Assert.True(true);
        }

	}

}


text:
{{-------------------------------------------------------- getEdit --------------}}
@section('getKeyEdit')
@if($action == 'getKeyEdit')

@if($displayType == "text/html")

Edit [{{$tableName}}::{{$pkName}}]

            Back
            Submit
            Delete
            Add

            @if(Options::get('debug'))
            Debug
            @endif
            Log

@endif

@yield('messages')

<?php
    $records = array();
    $records = $dataA;
    $headerPrinted = false;
?>

<form method="POST" id="dataForm" action="/db/keys">
    @include('skins::common.inc.keyedit_detail')

<input type="submit" class="btn" />

</form>

@endif
@stop


text:
class TSheets::Repos::Geolocations < TSheets::Repository
  url "/geolocations"
  model TSheets::Models::Geolocation
  actions :list, :add
  filter :ids, [ :integer ]
  filter :modified_before, :datetime
  filter :modified_since, :datetime
  filter :user_ids, [ :integer ]
  filter :group_ids, [ :integer ]
  filter :per_page, :integer
  filter :page, :integer
end


text: angular.module('app.dashboard', ['ngRoute']);


text:
Tabele przeszukiwania podstawiania adresów

<tt>canonical_maps</tt>

Ten parametr okre¶la fakultatywne tabele przeszukiwane przy podstawianiu
adresów. Podstawianie dotyczy zarówno adresów nadawców, jak i adresów
odbiorców, w nag³ówkach i na "kopercie". Jest to
zazwyczaj wykorzystywane porz±dkowania nieprawid³owych adresów
odziedziczonych po poprzednich systemach poczty lub do zastêpowania nazw
logowania przez <tt>Imie.Nazwisko</tt>. Szczegó³y znajdziesz
w podstawianiu kanonicznym.

Domy¶lnie nie s± wykonywane ¿adne podstawienia kanoniczne adresów.

Mo¿liwe rozs±dne warto¶ci:

 <tt>dbm:/etc/postfix/canonical</tt>

 <tt>hash:/etc/postfix/canonical</tt>

 <tt>hash:/etc/postfix/canonical, nis:canonical</tt>

 <tt>hash:/etc/postfix/canonical, netinfo:/canonical</tt>


text:
using Newtonsoft.Json;
using VkApi.Wrapper.Objects;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace VkApi.Wrapper.Responses
{
    public class DatabaseGetFacultiesResponse
    {
        ///<summary>
        /// Total number
        ///</summary>
        [JsonProperty("count")]
        public int Count { get; set; }
        [JsonProperty("items")]
        public DatabaseFaculty[] Items { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DSLOG_Reader_Library;

namespace DSLOG_Reader_2
{
    public partial class EnergyView : UserControl, SeriesViewObserver
    {
        private Dictionary<string, int[]> IdToPDPGroup;
        private Dictionary<int, double> EnergyCache = new Dictionary<int, double>();
        private const double MillToHour20 = 0.00000556;
        public EnergyView()
        {
            InitializeComponent();
            treeView1.DoubleBuffered(true);
        }

        public void SetEnergy(IEnumerable<DSLOGEntry> entries)
        {
            EnergyCache.Clear();
            if (entries == null) return;
            for (int i = 0; i < 24; i++)
            {
                EnergyCache.Add(i, entries.Where(en=> en.Voltage < 30).Sum(en => (en.GetPDPChannel(i) * MillToHour20) * en.Voltage)*3.6);
            }
            EnergyCache.Add(-1, EnergyCache.Sum(ser => ser.Value));
            DisplayEnergy();
        }

        public void AddEnergy(IEnumerable<DSLOGEntry> entries)
        {
            if (entries == null && EnergyCache.Count > 0) return;
            for (int i = 0; i < 16; i++)
            {
                EnergyCache[i] +=(entries.Where(en => en.Voltage < 30).Sum(en => (en.GetPDPChannel(i) * MillToHour20) * en.Voltage) * 3.6);
            }
            EnergyCache[-1] = EnergyCache.Where(ser=> ser.Key != -1).Sum(ser => ser.Value);
            DisplayEnergy();
        }

        private void ResetTreeView()
        {
            treeView1.Visible = false;
            foreach (TreeNode group in treeView1.Nodes)
            {
                foreach (TreeNode node in group.Nodes)
                {
                    int i = node.Text.LastIndexOf(": ");
                    if (i > 0) node.Text = node.Text.Substring(0, i);
                }
            }
        }

        private void DisplayEnergy()
        {
            //treeView1.BeginUpdate();
            ResetTreeView();
            if (EnergyCache.Count != 0 && IdToPDPGroup != null)
            {
                treeView1.Visible = true;
                foreach (TreeNode group in treeView1.Nodes)
                {
                    foreach (TreeNode node in group.Nodes)
                    {
                        if (node.Name.StartsWith(DSAttConstants.PDPPrefix))
                        {
                            node.Text = $"{node.Text}: { EnergyCache[int.Parse(node.Name.Replace(DSAttConstants.PDPPrefix, ""))].ToString("0.00")}kJ";
                        }
                        else if (node.Name == DSAttConstants.TotalPDP)
                        {
                            node.Text = $"{node.Text}:  { EnergyCache[-1].ToString("0.00")}kJ";
                        }
                        else if (node.Name.StartsWith(DSAttConstants.TotalPrefix))
                        {
                            node.Text = $"{node.Text}:  { IdToPDPGroup[node.Name].Sum(s => EnergyCache[s]).ToString("0.00")}kJ";
                        }

                    }
                }
            }
            //treeView1.EndUpdate();
        }

        public SeriesView SeriesViewObserving { get; set; }

        public void SetEnabledSeries(TreeNodeCollection groups)
        {
            //DisplayEnergy();
        }

        public void SetSeries(SeriesGroupNodes basic, SeriesGroupNodes pdp)
        {
            treeView1.Nodes.Clear();
            IdToPDPGroup = new Dictionary<string, int[]>();
            TreeNode otherGroup = basic.Find(g => g.Name == "other").ToTreeNode();
            otherGroup.Nodes.RemoveAt(0);
            treeView1.Nodes.Add(otherGroup);

            foreach (var group in pdp)
            {
                if (group.Childern.Count == 0) continue;
                int[] pdpIds = group.Childern.Where(n => n.Name.StartsWith(DSAttConstants.PDPPrefix)).Select(n => int.Parse(n.Name.Replace(DSAttConstants.PDPPrefix, ""))).ToArray();
                TreeNode newGroup = group.ToTreeNode();

                foreach (var node in group.Childern)
                {
                    if (node.Name.StartsWith(DSAttConstants.TotalPrefix))
                    {
                        IdToPDPGroup[node.Name] = pdpIds;
                    }
                    if (node.Name.StartsWith(DSAttConstants.DeltaPrefix))
                    {
                        newGroup.Nodes.RemoveByKey(node.Name);
                    }
                }

                foreach(TreeNode node in newGroup.Nodes)
                {
                    node.Text= node.Text + ": ";
                }
                treeView1.Nodes.Add(newGroup);
            }
            treeView1.ExpandAll();
            DisplayEnergy();
        }

        private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            e.Cancel = true;
        }
    }
}


text:
<?php
class Tools_Controller extends Template_Controller {

	protected $title = 'Nástroje WebArchivu';

	public function index()
	{
		$view = new View('tools');

		$this->template->content = $view;
	}

	public function metadata_generator($format = 'html')
	{
		$allowed_formats = array('xml', 'html', 'txt');
		if (! in_array($format, $allowed_formats))
		{
			throw new WaAdmin_Exception('Not supported metadata format', "Only {$allowed_formats} are currently allowed");
		}
		$view = new View('tools/metadata_generator');
		$view->resources = Resource_Model::factory('resource')->where(array('resource_status_id' => 5, 'id >' => 7000))->find_all();
		$view->format = $format;

		$file_name = 'media/metadata.'.$format;
		$file = file_put_contents($file_name, "\xEF\xBB\xBF".$view->render());

		if ($file == FALSE)
		{
			throw new WaAdmin_Exception('There has been problem metadata export.',
				'Please return back and try it again or contact system administrator');
		}

		download::force($file_name);
	}

}


text:
current_dir=${DOTFILES_CURRENT_SOURCE_DIR}
DOTNVIM="$HOME/.config/nvim"

# Create .config/nvim folder if needed
[ -d "$DOTNVIM" ] && mkdir -p $DOTNVIM

# Install nvim
dotfiles_install_package nvim

# Install config
dotfiles_install_component $current_dir $DOTNVIM

# Install vim plugins
nvim +PlugInstall


text:
[![Code Climate](https://codeclimate.com/github/noahd1/also_validates.png)](https://codeclimate.com/github/noahd1/also_validates)

# AlsoValidates

An ActiveModel validator that validates associated models, copying any errors from composed models up to their parent.

## Installation

Add this line to your application's Gemfile:

    gem 'also_validates'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install also_validates

## Usage

Given existing models with their own validations:

    class Beer
      include ActiveModel::Validations
      attr_accessor :hops
      validates_presence_of :hops

      def initialize(attrs = {})
        @hops = attrs[:hops]
      end
    end

    class Belly
      include ActiveModel::Validations
      attr_accessor :button
      validates_presence_of :button

      def initialize(attrs = {})
        @button = attrs[:button]
      end
    end

And you need a model that composes those models:

    class MonsterTruckRally
      include ActiveModel::Validations

      attr_accessor :beer, :belly, :truck_count

      validates_presence_of :truck_count
      also_validates :beer, :belly

      def initialize(attrs = {})
        @beer = attrs[:beer]
        @belly = attrs[:belly]
        @truck_count = attrs[:truck_count]
      end
    end

Calling `valid?` on an instance of monster truck rally, will run validations on both the monster truck rally as well as any models specified by `also_validates`. If there are any validation errors on the composed model, they are copied up (to the "base") of the parent model (in this case a MonsterTruckRally).

Note: Currently does not pass the attribute information (the field of the composed model) along to its parent. Errors are added to "base".

Only supported option currently is `allow_nil: true`:

    also_validates :beer, :belly, allow_nil: true

Which, as the option states, allows nil values and will not attempt to validate those models.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
![https://img.shields.io/badge/building-passing-brightgreen.svg](https://img.shields.io/badge/building-passing-brightgreen.svg)
> :page_facing_up: :department_store: A simple way to generate your virtual receipt

![Site Preview](http://i.imgur.com/MYyf08i.png)

## Motivation
I use to control my expanses on [Mobills](https://www.mobills.com.br/) (a personal finance application). So, every time when I go shopping I create an expanse with the **total** value. However, personally I prefer save what I bought as well, even thought the application doesn't have a specific field for it, only *more information* field.
Therefore, I write manually on some notepad each item and it value, copy this information and paste into it field.

## Solution
Based on motivation above, I decided create a static page with a simple form which receive:
- Product Name
- Quantity
- Price
- Calculate Method (refers to total calculate, in other words, if Price is total or just an item)

When you insert, the application create a product and insert in a list, which are storage in browser LocalStorage, and each item that are added, update total from the list of product.

## Concepts and Technologies
This project involves some interesting things like:

- [LocalStorage](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage)
- [Bulma CSS](http://bulma.io/)
- [ClipboardJS](https://clipboardjs.com)
- [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes)
- [Method Chaining](https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html)
- [Prototype Pattern](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype)

## Run locally

1. Clone the project
```sh
$ git clone https://github.com/raulfdm/food-list-creator.git
```
2. Move to project folder and install all dependencies
```sh
$ cd food-list-creator
$ npm install
```

3. Now, you can run a local server with the following command:
```sh
$ npm start
```

## Licence

[MIT](/blob/master/LICENCE.md)


text:
#include "config.h"
#include "HeapProfiler.h"

#include "HeapSnapshot.h"
#include "VM.h"

namespace JSC {

HeapProfiler::HeapProfiler(VM& vm)
    : m_vm(vm)
{
}

HeapProfiler::~HeapProfiler()
{
}

HeapSnapshot* HeapProfiler::mostRecentSnapshot()
{
    if (m_snapshots.isEmpty())
        return nullptr;
    return m_snapshots.last().get();
}

void HeapProfiler::appendSnapshot(std::unique_ptr<HeapSnapshot> snapshot)
{
    m_snapshots.append(WTFMove(snapshot));
}

void HeapProfiler::clearSnapshots()
{
    m_snapshots.clear();
}

void HeapProfiler::setActiveSnapshotBuilder(HeapSnapshotBuilder* builder)
{
    ASSERT(!!m_activeBuilder != !!builder);
    m_activeBuilder = builder;
}

} // namespace JSC


text:
<?xml version="1.0" encoding="UTF-8"?>
<tns:ScaleRegisterConfig xmlns:tns="http://www.tremolosecurity.com/scale"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.tremolosecurity.com/scale ../../../../../scale-config/src/main/resources/xml/scale-passwordreset.xsd ">
	<tns:serviceConfiguration keyStorePassword="#[SCALE_KEYSTORE_PASSWORD]"
		keyStorePath="/etc/scale/scaleKeystore.jks" unisonURL="https://#[SCALE_HOST_PORT]/"
		lookupAttributeName="uid" recaptcha="false" />
	<tns:UiConfig displayNameAttribute="cn" homeURL="/scale/" />
	<tns:frontPage>
		<tns:title>Register</tns:title>
		<tns:text>Register for this site</tns:text>
	</tns:frontPage>
	<tns:attributes>
	  	<tns:attribute name="sponsor" label="Department" controlType="list" required="true">
	  		<tns:listValue name="Sales" value="sales" />
	  		<tns:listValue name="Marketing" value="marketing" />
	  		<tns:listValue name="Engineering" value="eng" />
	  	</tns:attribute>
		<tns:attribute name="cn" label="Display Name" required="true" />
		<tns:attribute name="uid" label="User Login" required="true"></tns:attribute>
		<tns:attribute name="givenName" label="First Name" required="true" />
		<tns:attribute name="sn" label="Last Name" required="true" />
		<tns:attribute name="mail" label="Email Address" required="true" />
	</tns:attributes>
	<tns:termsAndConditions>
		In order to use this site you <b>MUST</b> accept these terms
	</tns:termsAndConditions>
	<tns:recaptcha>true</tns:recaptcha>
	<tns:uniqueAttribute>mail</tns:uniqueAttribute>
	<tns:uniqueAttribute>uid</tns:uniqueAttribute>
	<tns:workflowConfiguration className="com.tremolosecurity.scale.register.SimpleRegisterUser">
		<tns:initParams name="workflowName" value="PrintUserInfo" />
		<tns:initParams name="workflowReason" value="website registration" />

	</tns:workflowConfiguration>
</tns:ScaleRegisterConfig>


text:
import datetime
from pyspark import SparkContext
import time
import os
import sys
from cdr import CDR, Dataset#, check_complete_weeks_fast
from dateutil import rrule
from utils import quiet_logs

"""
ICP extraction (user profiling)

Given a CDR dataset and a set of geographical regions, it returns user profiles
for each spatial region. The results are tuples containing the following information:
<region>,<user_id>,<profile>.
More specifically, The analysis is divided in 4 week windows. Each window is divided in weeks,
weekdays or weekends, and 3 timeslots:
t0=[00:00-08:00], t1=[08:00-19:00], t2=[19:00-24:00].
The <profile> is a 24 element list containing the sum of user calls for such a division.
The column index for each division is: <week_idx> * 6 + <is_weekend> * 3 + <timeslot>
where <is_weekend> can be 0 or 1.

Usage:
    $SPARK_HOME/bin/spark-submit --py-files cdr.py user_profiling.py <dataset path> \
        <spatial region file> <format file> <format date> <area identifier>

Parameter:
    dataset path: path on hdfs where the dataset is located
    spatial region file: csv files with the association GSM antenna --> spatial region
    field2col: file containing the format of the csv files composing the dataset
    format date: the date format (according to python datetime module) of the cdr
    tag: a string used to name the results files
    start_date: The analysis starting date. Expected input %Y-%m-%d
    end_date: The analysis ending date. Expected input %Y-%m-%d

Example:
      $SPARK_HOME/bin/spark-submit --py-files cdr.py user_profiling.py dataset_simulated ../spatial_regions/aree_roma.csv field2col_simulated.csv %Y-%m-%d roma

Output: profiles will be saved in this path: /profiles/<area identifier>-<year>_<week>. Week is the first week of the corresponding
4 weeks block analyzed. These two parameters are computed inside the script, by scanning all the dataset and assigning each file to the
corresponding week.
"""

ARG_DATE_FORMAT='%Y-%m-%d'

########################functions##################################
def normalize(profilo):
    # normalize calls made on weekend or weekdays

    return [(region, week_idx, is_we, day_time, count * 1.0 / (2 if is_we == 1 else 5))
            for region, week_idx, is_we, day_time, count in profilo]

def array_carretto(profilo, weeks, user_id):
    # flll the list of calls in the basket with zeros where there are no dataV
    for munic in set([x[0] for x in profilo]):
        # settimana, work/we,timeslice, count normalizzato

        obs = [x[1:] for x in profilo if x[0] == munic]
        obs = sorted(obs, key=lambda d: sum(
            [j[3] for j in obs if j[0] == d[0]]), reverse=True)

        carr = [0 for x in range(len(weeks) * 2 * 3)]

        for w, is_we, t, count in obs:
            idx = (w - 1) * 6 + is_we * 3 + t
            carr[idx] = count
        yield munic, user_id, carr

##########################################################################
folder = sys.argv[1]
spatial_division = sys.argv[2]
field2col=sys.argv[3]
date_format=sys.argv[4]
tag=sys.argv[5]
start_date = datetime.datetime.strptime(sys.argv[6], ARG_DATE_FORMAT)
end_date = datetime.datetime.strptime(sys.argv[7], ARG_DATE_FORMAT)

# spatial division: cell_id->region of interest

file = open(spatial_division)
# converting cell to municipality
cell2municipi = {
    k: v for k,
    v in [
        (x.split(';')[0],
         x.split(';')[1].replace(
            "\n",
            "")) for x in file.readlines()]}

sc = SparkContext()
quiet_logs(sc)

start = time.time()
rddlist = []

field2col = {k: int(v) for k, v in [x.strip().split(',') for x in open(field2col)]}

#files, weeks = check_complete_weeks_fast(
#    folder,
#    lambda (n, d): d['type'] == 'FILE', # keep only files
#    lambda n: datetime.datetime.strptime(n.split('.')[0].split('_')[-1], '%Y%m%d').isocalendar()[:-1]
#)

weeks = [d.isocalendar()[:2] for d in rrule.rrule(
    rrule.WEEKLY, dtstart=start_date, until=end_date
)]

data = sc.textFile(folder) \
    .map(lambda row: CDR.from_string(row, field2col, date_format)) \
    .filter(lambda x: x is not None) \
    .filter(lambda x: x.valid_region(cell2municipi)) \
    .cache()

#for t in weeks[::2]:
for t in weeks[::4]:
    idx = weeks.index(t)
    window = weeks[idx:idx + 4]
    dataset = Dataset(data.filter(lambda x: x.week in window))
    r = dataset.data.map(lambda x: (x.user_id, x.region(cell2municipi),
                                     window.index(x.week), x.is_we(),
                                     x.day_of_week(), x.day_time())) \
        .distinct() \
        .map(lambda (user_id, region, week_idx, is_we, day_of_week, day_time):
             ((user_id, region, week_idx, is_we, day_time), 1)) \
        .reduceByKey(lambda x, y: x + y) \
        .map(lambda  ((user_id, region, week_idx, is_we, day_time), count):
             (user_id, [[region, week_idx, is_we, day_time, count]])) \
        .reduceByKey(lambda x, y: x + y)

    #r = r.map(lambda (user_id, l): (user_id, sorted(l, key=lambda w: (
    #    w[0], sum([z[4] for z in l if z[1] == w[1]])), reverse=True)))

    r = r.map(lambda (user_id, l): (user_id, normalize(l)))
    r = r.flatMap(
        lambda user_id_l: array_carretto(
            user_id_l[1],
            window,
            user_id_l[0]))

    output = '/profiles/%s/%s' % (tag, '_'.join(map(str, window[0])))
    os.system("$HADOOP_HOME/bin/hadoop fs -rm -r %s" % output)
    r.saveAsTextFile(output)

print "elapsed time", time.time() - start


text:
namespace PatientManagement.Common {
    export interface UserPreferenceRetrieveRequest extends Serenity.ServiceRequest {
        PreferenceType?: string;
        Name?: string;
    }
}


text:
<?php

declare(strict_types = 1);

namespace Rx\Notification;

use Rx\ObserverInterface;
use Rx\Notification;

class OnNextNotification extends Notification
{
    private $value;

    public function __construct($value)
    {
        parent::__construct('N');

        $this->value = $value;
    }

    protected function doAcceptObservable(ObserverInterface $observer)
    {
        $observer->onNext($this->value);
    }

    protected function doAccept($onNext, $onError, $onCompleted)
    {
        $onNext($this->value);
    }

    public function __toString(): string
    {
        return 'OnNext(' . json_encode($this->value) . ')';
    }

    public function equals($other): bool
    {
        if (($other instanceof $this) && is_object($this->value) && is_object($other->value)) {
            if ($this->value instanceof $other->value && method_exists($this->value, "equals")) {
                return $this->value->equals($other->value);
            }
        }

        return (string)$this === (string)$other;
    }
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0; url=/docs/core-concepts/metrics/">
    <link rel="canonical" href="/docs/core-concepts/metrics/" />
  </head>
  <script>
    window.location.href = '/docs/core-concepts/metrics/' + window.location.search + window.location.hash;
  </script>
</html>


text:
include(joinpath(@__DIR__, "bind_generator.jl"))

# Read in the API definition macros from the definitions file
defs = read(joinpath(@__DIR__, "api_defs.jl"), String)
# Have Julia expand/run the @bind macro to generate expressions for all of the functions
exprs = Base.include_string(@__MODULE__, "@macroexpand1 begin\n" * defs * "\nend", "api_defs.jl")
# Insert the conditional version helper expression
prepend!(exprs.args, _libhdf5_build_ver_expr.args)
Base.remove_linenums!(exprs)

# Definitions which are not automatically generated, but should still be documented as
# part of the raw low-level API:
append!(bound_api["H5P"],
        ["h5p_get_class_name"])   # defined in src/api/helpers.jl
append!(bound_api["H5T"],
        ["h5t_get_member_name",   # defined in src/api/helpers.jl
         "h5t_get_tag"])          # defined in src/api/helpers.jl

# Now dump the text representation to disk
open(joinpath(@__DIR__, "..", "src", "api", "functions.jl"), "w") do fid
    println(fid, """
# This file is autogenerated by HDF5.jl's `gen/gen_wrappers.jl` and should not be editted.
#
# To add new bindings, define the binding in `gen/api_defs.jl`, re-run
# `gen/gen_wrappers.jl`, and commit the updated `src/api/functions.jl`.
""")
    function triplequote(s::String, indent = "", prefix = "")
        ret = indent * prefix * "\"\"\"\n"
        for l in eachline(IOBuffer(s))
            ret *= isempty(l) ? "\n" : indent * l * "\n"
        end
        ret *= indent * "\"\"\"\n"
        return ret
    end
    ismacro(ex, sym, n = 0) = isexpr(ex, :macrocall) && length(ex.args) >= n + 2 &&
                              ex.args[1] == sym
    for funcblock in exprs.args
        if ismacro(funcblock, Symbol("@doc"), 2)
            # Pretty print the doc macro as just a juxtaposed doc string and function
            # definition; the `@doc` construction is necessary in AST form for the docs
            # to be included in interactive use of `@bind`, but in source form we can
            # rely on Julia's parsing behavior.
            print(fid, triplequote(funcblock.args[3]), funcblock.args[4], "\n\n")
        elseif ismacro(funcblock, Symbol("@static"), 1) &&
               isexpr(funcblock.args[3], :if, 2) &&
               ismacro(funcblock.args[3].args[2], Symbol("@doc"), 2)
            # Within a @static block, we have to keep the @doc prefix, but we can still
            # switch to triple-quoting and there's special parsing to allow the function
            # definition to be on the next line.
            #
            # Work around the expression printer in this more complex case by printing
            # to a buffer and string-replacing a sentinel value
            docstr = funcblock.args[3].args[2].args[3]
            funcblock.args[3].args[2].args[3] = "SENTINEL_DOC"
            buf = sprint(print, funcblock)
            # Two-step deindent since `r"^\s{4}(\s{4})?"m => s"\1"` errors: see JuliaLang/julia#31456
            buf = replace(buf, r"^\s{4}"m => s"") # deindent
            buf = replace(buf, r"^(\s{4})\s{4}"m => s"\1") # deindent
            # Now format the doc string and replace (note need to indent `function`)
            buf = replace(buf, r"^\s+@doc \"SENTINEL_DOC\" "m =>
                               triplequote(docstr, " "^4, "@doc ") * " "^4)
            print(fid, buf, "\n\n")
        else
            # passthrough
            print(fid, funcblock, "\n\n")
        end
    end
end

# Also generate auto-docs that simply list all of the bound API functions
apidocs = ""
for (mod, desc, urltail) in (
    ("H5", "General Library Functions", "Library"),
    ("H5A", "Attribute Interface", "Attributes"),
    ("H5D", "Dataset Interface", "Datasets"),
    ("H5E", "Error Interface", "Error+Handling"),
    ("H5F", "File Interface", "Files"),
    ("H5G", "Group Interface", "Groups"),
    ("H5I", "Identifier Interface", "Identifiers"),
    ("H5L", "Link Interface", "Links"),
    ("H5O", "Object Interface", "Objects"),
    ("H5P", "Property Interface", "Property+Lists"),
    ("H5R", "Reference Interface", "References"),
    ("H5S", "Dataspace Interface", "Dataspaces"),
    ("H5T", "Datatype Interface", "Datatypes"),
    ("H5Z", "Filter Interface", "Filters"),
    ("H5DO", "Optimized Functions Interface", "Optimizations"),
    ("H5DS", "Dimension Scale Interface", "Dimension+Scales"),
    ("H5LT", "Lite Interface", "Lite"),
    ("H5TB", "Table Interface", "Tables"),
    )
    global apidocs
    funclist = sort!(bound_api[mod])
    index = join(["- [`$f`](@ref $f)" for f in funclist], "\n")
    funcs = join(funclist, "\n")
    apidocs *= """
        ---

        ## [`$mod`](https://portal.hdfgroup.org/display/HDF5/$urltail) — $desc
        $index
        ```@docs
        $funcs
        ```

        """
end

open(joinpath(@__DIR__, "..", "docs", "src", "api_bindings.md"), "w") do fid
    write(fid,
"""
```@raw html
<!-- This file is auto-generated and should not be manually editted. To update, run the
gen/gen_wrappers.jl script -->
```
```@meta
CurrentModule = HDF5.API
```

# Low-level library bindings

At the lowest level, `HDF5.jl` operates by calling the public API of the HDF5 shared
library through a set of `ccall` wrapper functions.
This page documents the function names and nominal C argument types of the API which
have bindings in this package.
Note that in many cases, high-level data types are valid arguments through automatic
`ccall` conversions.
For instance, `HDF5.Datatype` objects will be automatically converted to their `hid_t` ID
by Julia's `cconvert`+`unsafe_convert` `ccall` rules.

There are additional helper wrappers (often for out-argument functions) which are not
documented here.

$apidocs
"""
    )
end

nothing


text:
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true" ng-click="close()">×</button>

{{'PROPERTY.PROPERTY.EDIT.TITLE' | translate}} "{{property.title | translate}}"

            	        	{{'PROPERTY.EVENTLISTENERS.EVENTS' | translate}}

            	            	  <select id="eventField" class="form-control" ng-model="eventDefinition.event" ng-change="listenerDetailsChanged()"
                                          style="display:inline-block; width:80%;margin-bottom: 10px;">
                                  <option title="{{'EVENT_TYPE.ACTIVITY.COMPENSATE.TOOLTIP' | translate}}">ACTIVITY_COMPENSATE</option>
                                  <option title="{{'EVENT_TYPE.ACTIVITY.COMPLETED.TOOLTIP' | translate}}">ACTIVITY_COMPLETED</option>
                                  <option title="bla">ACTIVITY_ERROR_RECEIVED</option>
                                  <option>ACTIVITY_MESSAGE_RECEIVED</option>
                                  <option>ACTIVITY_SIGNALED</option>
                                  <option>ACTIVITY_STARTED</option>
                                  <option>ENGINE_CLOSED</option>
                                  <option>ENGINE_CREATED</option>
                                  <option>ENTITY_ACTIVATED</option>
                                  <option>ENTITY_CREATED</option>
                                  <option>ENTITY_DELETED</option>
                                  <option>ENTITY_INITIALIZED</option>
                                  <option>ENTITY_SUSPENDED</option>
                                  <option>ENTITY_UPDATED</option>
                                  <option>JOB_EXECUTION_FAILURE</option>
                                  <option>JOB_EXECUTION_SUCCESS</option>
                                  <option>JOB_RETRIES_DECREMENTED</option>
                                  <option title="{{'EVENT_TYPE.MEMBERSHIP.CREATED.TOOLTIP' | translate}}">MEMBERSHIP_CREATED</option>
                                  <option title="{{'EVENT_TYPE.MEMBERSHIP.DELETED.TOOLTIP' | translate}}">MEMBERSHIP_DELETED</option>
                                  <option title="{{'EVENT_TYPE.MEMBERSHIPS.DELETED.TOOLTIP' | translate}}">MEMBERSHIPS_DELETED</option>
                                  <option title="{{'EVENT_TYPE.TASK.ASSIGNED.TOOLTIP' | translate}}">TASK_ASSIGNED</option>
                                  <option title="{{'EVENT_TYPE.TASK.COMPLETED.TOOLTIP' | translate}}">TASK_COMPLETED</option>
                                  <option>TIMER_FIRED</option>
                                  <option title="{{'EVENT_TYPE.UNCAUGHT.BPMNERROR.TOOLTIP' | translate}}">UNCAUGHT_BPMN_ERROR</option>
                                  <option title="{{'EVENT_TYPE.VARIABLE.CREATED.TOOLTIP' | translate}}">VARIABLE_CREATED</option>
                                  <option title="{{'EVENT_TYPE.VARIABLE.DELETED.TOOLTIP' | translate}}">VARIABLE_DELETED</option>
                                  <option title="{{'EVENT_TYPE.VARIABLE.UPDATED.TOOLTIP' | translate}}">VARIABLE_UPDATED</option>
            	               	</select>
            		             0" class="glyphicon glyphicon-minus clickable-property" ng-click="removeEventValue($index)"
                                   style="margin: 5px 0 5px 10px; font-size: 16px; cursor:pointer;">

                                <input type="checkbox" id="rethrowField" class="checkbox" ng-model="selectedListener.rethrowEvent" ng-change="listenerDetailsChanged()" style="display:inline-block;"/>
                                {{'PROPERTY.EVENTLISTENERS.RETHROW' | translate}}

            		   		 {{'PROPERTY.EVENTLISTENERS.CLASS' | translate}}
            		   		<input type="text" id="classField" class="form-control" ng-model="selectedListener.className" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.CLASS.PLACEHOLDER' | translate}}" />

            		   		{{'PROPERTY.EVENTLISTENERS.DELEGATEEXPRESSION' | translate}}
            		   		<input type="text" id="delegateExpressionField" class="form-control" ng-model="selectedListener.delegateExpression" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.DELEGATEEXPRESSION.PLACEHOLDER' | translate}}" />

            		   		{{'PROPERTY.EVENTLISTENERS.ENTITYTYPE' | translate}}
            		   		<input type="text" id="entityTypeField" class="form-control" ng-model="selectedListener.entityType" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.ENTITYTYPE.PLACEHOLDER' | translate}}" />

            		   		{{'PROPERTY.EVENTLISTENERS.RETHROWTYPE' | translate}}
            		   		<select id="rethrowTypeField" class="form-control" ng-model="selectedListener.rethrowType" ng-change="rethrowTypeChanged()">
                                <option>error</option>
                                <option>message</option>
                                <option>signal</option>
                                <option>globalSignal</option>
                            </select>

            		   		{{'PROPERTY.EVENTLISTENERS.ERRORCODE' | translate}}
            		   		<input type="text" id="errorCodeField" class="form-control" ng-model="selectedListener.errorcode" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.ERRORCODE.PLACEHOLDER' | translate}}" />

            		   		{{'PROPERTY.EVENTLISTENERS.MESSAGENAME' | translate}}
            		   		<input type="text" id="messageNameField" class="form-control" ng-model="selectedListener.messagename" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.MESSAGENAME.PLACEHOLDER' | translate}}" />

            		   		{{'PROPERTY.EVENTLISTENERS.SIGNALNAME' | translate}}
            		   		<input type="text" id="signalNameField" class="form-control" ng-model="selectedListener.signalname" ng-change="listenerDetailsChanged()" placeholder="{{'PROPERTY.EVENTLISTENERS.SIGNALNAME.PLACEHOLDER' | translate}}" />

PROPERTY.EVENTLISTENERS.UNSELECTED

                <button ng-click="cancel()" class="btn btn-primary" translate>ACTION.CANCEL</button>
                <button ng-click="save()" class="btn btn-primary" translate>ACTION.SAVE</button>


text:
package com.orionplatform.user_management.authentication.login.tasks;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.orionplatform.calendar.CalendarService;
import com.orionplatform.calendar.datetime.DateTime;
import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.data.data_access.user.OrionUsersDAO;
import com.orionplatform.data.data_access.user.authentication.OrionUserFailedLoginAttemptsDAO;
import com.orionplatform.data.data_model.user.OrionAuthorityModel;
import com.orionplatform.data.data_model.user.authentication.OrionUserFailedLoginAttemptsModel;

public class ProcessFailedLoginAttemptsTask extends Orion
{
    public static synchronized void run(OrionAuthorityModel authority, boolean enableMonitoringOfFailedLoginAttempts, int maximumNumberOfMinutesToMonitorFailedLoginAttempts) throws UsernameNotFoundException
    {
        if(enableMonitoringOfFailedLoginAttempts)
        {
            OrionUserFailedLoginAttemptsModel failedLoginAttempts = OrionUserFailedLoginAttemptsDAO.getUserFailedLoginAttemptsByUserID(authority.getUserID());

            if(failedLoginAttempts != null)
            {
                if(failedLoginAttempts.getAccountDisabled())
                {
                    DateTime currentDatetime = CalendarService.getCurrentDatetime();
                    DateTime firstFailedLoginAttemptDatetime = DateTime.of(failedLoginAttempts.getFirstFailedLoginAttemptDate(), failedLoginAttempts.getFirstFailedLoginAttemptTime());
                    DateTime datetimeToStopMonitoringFailedLoginAttempts = CalendarService.addMinutesToDatetime(firstFailedLoginAttemptDatetime, maximumNumberOfMinutesToMonitorFailedLoginAttempts);
                    boolean isCurrentDatetimeAfterOrEqualsFailedLoginAttemptDatetimeToStopMonitoring = CalendarService.isDateAfterOrEqualsAnother(currentDatetime, datetimeToStopMonitoringFailedLoginAttempts);

                    if(isCurrentDatetimeAfterOrEqualsFailedLoginAttemptDatetimeToStopMonitoring)
                    {
                        enableUserAccount(authority);
                        failedLoginAttempts.setAccountDisabled(false);
                        updateUserFailedLoginAttempt(authority, failedLoginAttempts);
                    }
                    else
                    {
                        throw new UsernameNotFoundException("User account is disabled because of many failed login attempts.");
                    }
                }
            }
        }
    }

    private static synchronized void updateUserFailedLoginAttempt(OrionAuthorityModel authority, OrionUserFailedLoginAttemptsModel failedLoginAttempts) throws UsernameNotFoundException
    {
        int numberOfrowsAffected = OrionUserFailedLoginAttemptsDAO.updateUserFailedLoginAttempt(failedLoginAttempts);

        if(numberOfrowsAffected == 0)
        {
            throw new UsernameNotFoundException(String.format("Could not update failed login attempt for userID '{}'.", authority.getUserID()));
        }
    }

    private static synchronized void enableUserAccount(OrionAuthorityModel authority) throws UsernameNotFoundException
    {
        int numberOfrowsAffected = OrionUsersDAO.enableUserAccountByUserID(authority.getUserID());

        if(numberOfrowsAffected == 0)
        {
            throw new UsernameNotFoundException(String.format("Could not enable account of userID '{}'.", authority.getUserID()));
        }
    }
}