text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_GLOBALNORM_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_GLOBALNORM_HPP_INCLUDED

#include <nt2/include/functor.hpp>
#include <nt2/sdk/meta/as_real.hpp>
#include <boost/mpl/int.hpp>

namespace nt2 { namespace tag
  {
    /*!
      @brief globalnorm generic tag

      Represents the globalnorm function in generic contexts.

      @par Models:
      Hierarchy
    **/
    struct globalnorm_ : tag::formal_
    {
      /// @brief Parent hierarchy
      typedef boost::dispatch::tag::formal_ parent;
    };
  }

  /*!
    @brief Global norm

    Computes the norm of a whole table expression with static or dynamic choice
    of the norm computation formula.

    Call protocols to globalnorm are summarized in the following table. We advise to use static
    calls whenever possible as it prevents cascaded run-time if clauses and goes directly
    to the right call at execution.

    @code
    |--------------------|-------------------|------------------------------|-------------------|
    | mnorm(a0, p)                                                                              |
    |--------------------|-------------------|------------------------------|-------------------|
    |    static p        |  dynamic p        |     formula (pseudo-code)    |  equivalent to    |
    |--------------------|-------------------|------------------------------|-------------------|
    | nt2::one_          | 1                 |       sum(abs(x(_)))         | globalnorm1(x)    |
    | nt2::two_          | 2                 |   sqrt(sum(sqr(abs(x(_)))))  | globalnorm2(x)    |
    |    -               | p (positive)      |    sum(abs(x)^p)^(1/p)       | globalnormp(x,p)  |
    | nt2::inf_          | nt2::Inf<T>()     |       max(abs((x))           | globalnorminf(x)  |
    | nt2::fro_          | -1                |   sqrt(sum(sqr(abs(x(_)))))  | globalnormfro(x)  |
    |--------------------|-------------------|------------------------------|-------------------|
    | mnorm<p>(a0)                                                                              |
    |--------------------|-------------------|------------------------------|-------------------|
    |    static p        |                   |     matrix                   |                   |
    |--------------------|-------------------|------------------------------|-------------------|
    | nt2::tag::one_ or 1|        -          |       sum(abs(x(_)))         |  globalnorm1(x)   |
    | nt2::tag::two_ or 2|        -          |   sqrt(sum(sqr(abs(x(_)))))  |  globalnorm2(x)   |
    | p  (integer only)  |        -          |    sum(abs(x)^p)^(1/p)       |  globalnormp(x,p) |
    | nt2::tag::inf_     |        -          |       max(abs((x))           |  globalnorminf(x) |
    | nt2::tag::fro_     |        -          |   sqrt(sum(sqr(abs(x(_)))))  |  globalnormfro(x) |
    |--------------------|-------------------|------------------------------|-------------------|
    @endcode

    @par Semantic:

    For any expression @c a0 of type @c A0, the following call:

    @code
    as_real<A0::value_type>::type x = globalnorm(a0);
    @endcode

    is equivalent to:

    @code
    as_real<A0::value_type>::type x = globalnorm2(a0);
    @endcode

    For any expression @c a0 of type @c A0 and any floating point value @c p, the
    following call:

    @code
    as_real<A0::value_type>::type x = globalnorm(a0,p);
    @endcode

    is equivalent to:

    @code
    as_real<A0::value_type>::type x = globalnormp(a0,p);
    @endcode

    if @c p is finite and to :

    @code
    as_real<A0::value_type>::type x = globalmax(abs(a0));
    @endcode

    if @c is +Inf and to :

    @code
    as_real<A0::value_type>::type x = globalmin(abs(a0));
    @endcode

    if @c p is -Inf.

    @note If 0 < p < 1 or p = -inf, globalnorm does not share the properties that
    define a mathematical norm,  but only a quasi-norm if  0 < p < 1 and a notation
    facility for p = -inf.

    @par Static Interface

    globalnorm can also be invoked with a template parameter which is either a
    functor tag describing the constant value to use instead of @c p or an
    Integral Constant. For example,

    @code
    as_real<A0::value_type>::type x = globalnorm<tag::two_>(a0);
    @endcode

    is equivalent to:

    @code
    as_real<A0::value_type>::type x = globalnorm2(a0);
    @endcode

    Similarly,

    @code
    as_real<A0::value_type>::type x = globalnorm<5>(a0);
    @endcode

    is equivalent to:

    @code
    as_real<A0::value_type>::type x = globalnormp(a0,5);
    @endcode

    @note Whenever a constant functor tag or an Integral Constant is used, compile
    time optimization is performed (if available) so the correct variant of globalnorm is
    called. For example, calls similar to globalnorm<2>(a0) will invoke
    globalnorm2(a0) instead of globalnormp(a0, 2), and globalnorm<5>(a0) will simply
    invoke directly globalnormp(a0, 5) but without any runtime selection.

    @param a0 Expression to compute the norm of
    @param a1 Type of norm to compute
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(nt2::tag::globalnorm_, globalnorm, 2)

  /// @overload
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(nt2::tag::globalnorm_, globalnorm, 1)

  /// @overload
  template<typename Tag, typename A0>
  BOOST_FORCEINLINE typename meta::as_real<typename A0::value_type>::type
  globalnorm(const A0& a0)
  {
    return globalnorm(a0, nt2::meta::as_<Tag>());
  }

  /// @overload
  template<int Value, typename A0>
  BOOST_FORCEINLINE typename meta::as_real<typename A0::value_type>::type
  globalnorm(const A0& a0)
  {
    return globalnorm(a0, boost::mpl::int_<Value>() );
  }
}

#endif


text:
from __future__ import absolute_import, division, print_function

import os

import pywatchman
import WatchmanTestCase

try:
    import unittest2 as unittest
except ImportError:
    import unittest

def is_root():
    return hasattr(os, "geteuid") and os.geteuid() == 0

@WatchmanTestCase.expand_matrix
class TestPerms(WatchmanTestCase.WatchmanTestCase):
    def checkOSApplicability(self):
        if os.name == "nt":
            self.skipTest("N/A on Windows")

    @unittest.skipIf(is_root(), "N/A if root")
    def test_permDeniedSubDir(self):
        root = self.mkdtemp()
        subdir = os.path.join(root, "subdir")
        os.mkdir(subdir)
        os.chmod(subdir, 0)
        self.watchmanCommand("watch", root)
        res = self.watchmanCommand(
            "query", root, {"expression": ["exists"], "fields": ["name"]}
        )
        self.assertRegex(res["warning"], "Marking this portion of the tree deleted")

    @unittest.skipIf(is_root(), "N/A if root")
    def test_permDeniedRoot(self):
        root = self.mkdtemp()
        os.chmod(root, 0)
        with self.assertRaisesRegex(pywatchman.CommandError, "(open|opendir|realpath)"):
            self.watchmanCommand("watch", root)

redpajama_set_name: RedPajamaGithub


text:
const char LOGFILE[] = "log.txt";
const char* LABELS[] = { "TRACE", "DEBUG", "INFO ", "WARN ", "ERROR" };

void print(const std::string& msg, int level) {
	// To reduce clutter, only tag warnings and errors
	if (level >= Log::LEVEL_WARN)
		std::cout << LABELS[level] << ": ";
	std::cout << msg << std::endl;
}

void log(const std::string& msg, int level) {
	if (level >= Log::level) {
		// Skip logging if msg is a duplicate of the previous msg.
		// This helps alleviate log bloat
		static std::string lastMsg;
		if (msg == lastMsg) { return; }
		lastMsg = msg;

		// Generate timestamp.
		std::time_t now = std::time(NULL);
		std::tm ptm;
		localtime_s(&ptm, &now);
		char timestamp[32];
		std::strftime(timestamp, 32, "[%H:%M:%S ", &ptm);

		// Write to log file.
		std::ofstream f(LOGFILE, std::ios::app);
		f << timestamp << LABELS[level] << "] " << msg << std::endl;
	}
}

void logAndPrint(const char* fmt, va_list args, int level) {
	char buf[250];
	vsprintf_s(buf, fmt, args);
	log(buf, level);
	print(buf, level);
}

int Log::level = Log::LEVEL_WARN;

// All log functions look similar, so we define them using a macro
#define LOGFUNC(name, level) \
	void Log:: ## name ## (const char* fmt, ...) { \
		va_list args; \
		va_start(args, fmt); \
		logAndPrint(fmt, args, LEVEL_ ## level); \
		va_end(args); \
	}

LOGFUNC(error, ERROR)
LOGFUNC(warn, WARN)
LOGFUNC(info, INFO)
LOGFUNC(debug, DEBUG)
LOGFUNC(trace, TRACE)


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(parent, inputConfig) {
  // [START retail_v2beta_generated_UserEventService_ImportUserEvents_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. `projects/1234/locations/global/catalogs/default_catalog`
   */
  // const parent = 'abc123'
  /**
   *  Required. The desired input location of the data.
   */
  // const inputConfig = {}
  /**
   *  The desired location of errors incurred during the Import. Cannot be set
   *  for inline user event imports.
   */
  // const errorsConfig = {}

  // Imports the Retail library
  const {UserEventServiceClient} = require('@google-cloud/retail').v2beta;

  // Instantiates a client
  const retailClient = new UserEventServiceClient();

  async function callImportUserEvents() {
    // Construct request
    const request = {
      parent,
      inputConfig,
    };

    // Run request
    const [operation] = await retailClient.importUserEvents(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callImportUserEvents();
  // [END retail_v2beta_generated_UserEventService_ImportUserEvents_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace AltinnApp.iOS
{
    public class FlyoutTablesource : UITableViewSource
    {
        private readonly CorePlatform.Translate _trans;

        public FlyoutTablesource()
        {
            _trans = new CorePlatform.Translate();
        }

        public override int RowsInSection(UITableView tableview, int section)
        {
            return 5;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            string cellIdentifier = "Cell";
            string cellLabel = string.Empty;

            switch (indexPath.Row)
            {
                case 0:

                    cellIdentifier = "Inbox";
                    cellLabel = _trans.GetString("MessageboxController_InboxHeader");
                    break;

                case 1:
                    cellIdentifier = "Archive";
                    cellLabel = _trans.GetString("MessageboxController_ArchiveHeader");
                    break;
                case 2:
                    cellIdentifier = "Settings";
                    cellLabel = _trans.GetString("SettingsController_Header");
                    break;
                case 3:
                    cellIdentifier = "Contact";
                    cellLabel = _trans.GetString("ContactController_Header");
                    break;
                case 4:
                    cellIdentifier = "Feedback";
                    cellLabel = _trans.GetString("FeedbackController_Header");
                    break;
            }

            UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
            var selectedBackgroundView = new UIView(cell.Frame) { BackgroundColor = UIColor.FromRGB(73, 73, 73) };
            cell.SelectedBackgroundView = selectedBackgroundView;

			cell.BackgroundColor = UIColor.FromRGB (108, 108, 108);
			var backgroundView = new UIView(cell.Frame) { BackgroundColor = UIColor.FromRGB(108, 108, 108) };
            cell.BackgroundView = backgroundView;

			cell.ContentView.BackgroundColor = UIColor.FromRGB(108, 108, 108);

            cell.TextLabel.Text = cellLabel;

            return cell;
        }
    }
}


text:
package org.clafer.ast;

import static org.clafer.ast.Asts.arithm;
import static org.clafer.ast.Asts.card;
import static org.clafer.ast.Asts.compare;
import static org.clafer.ast.Asts.concat;
import static org.clafer.ast.Asts.connected;
import static org.clafer.ast.Asts.decl;
import static org.clafer.ast.Asts.diff;
import static org.clafer.ast.Asts.domainRestriction;
import static org.clafer.ast.Asts.downcast;
import static org.clafer.ast.Asts.ifThenElse;
import static org.clafer.ast.Asts.inter;
import static org.clafer.ast.Asts.inverse;
import static org.clafer.ast.Asts.join;
import static org.clafer.ast.Asts.joinParent;
import static org.clafer.ast.Asts.joinRef;
import static org.clafer.ast.Asts.length;
import static org.clafer.ast.Asts.max;
import static org.clafer.ast.Asts.membership;
import static org.clafer.ast.Asts.min;
import static org.clafer.ast.Asts.minus;
import static org.clafer.ast.Asts.mod;
import static org.clafer.ast.Asts.not;
import static org.clafer.ast.Asts.prefix;
import static org.clafer.ast.Asts.product;
import static org.clafer.ast.Asts.quantify;
import static org.clafer.ast.Asts.rangeRestriction;
import static org.clafer.ast.Asts.suffix;
import static org.clafer.ast.Asts.sum;
import static org.clafer.ast.Asts.test;
import static org.clafer.ast.Asts.transitiveClosure;
import static org.clafer.ast.Asts.union;
import static org.clafer.ast.Asts.upcast;

/**
 *
 * @param <T> the parameter type
 * @author jimmy
 */
public abstract class AstExprRewriter<T> implements AstExprVisitor<T, AstExpr> {

    public AstBoolExpr rewrite(AstBoolExpr expr, T t) {
        return (AstBoolExpr) expr.accept(this, t);
    }

    public AstBoolExpr[] rewrite(AstBoolExpr[] exprs, T t) {
        AstBoolExpr[] rewritten = new AstBoolExpr[exprs.length];
        for (int i = 0; i < rewritten.length; i++) {
            rewritten[i] = rewrite(exprs[i], t);
        }
        return rewritten;
    }

    public AstSetExpr rewrite(AstSetExpr expr, T t) {
        return (AstSetExpr) expr.accept(this, t);
    }

    public AstSetExpr[] rewrite(AstSetExpr[] exprs, T t) {
        AstSetExpr[] rewritten = new AstSetExpr[exprs.length];
        for (int i = 0; i < rewritten.length; i++) {
            rewritten[i] = rewrite(exprs[i], t);
        }
        return rewritten;
    }

    @Override
    public AstExpr visit(AstThis ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstGlobal ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstConstant ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstStringConstant ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstJoin ast, T a) {
        return join(rewrite(ast.getLeft(), a), ast.getRight());
    }

    @Override
    public AstExpr visit(AstJoinParent ast, T a) {
        return joinParent(rewrite(ast.getChildren(), a));
    }

    @Override
    public AstExpr visit(AstJoinRef ast, T a) {
        return joinRef(rewrite(ast.getDeref(), a));
    }

    @Override
    public AstExpr visit(AstNot ast, T a) {
        return not(rewrite(ast.getExpr(), a));
    }

    @Override
    public AstExpr visit(AstMinus ast, T a) {
        return minus(rewrite(ast.getExpr(), a));
    }

    @Override
    public AstExpr visit(AstCard ast, T a) {
        return card(rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstMax ast, T a) {
        return max(rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstMin ast, T a) {
        return min(rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstSetTest ast, T a) {
        return test(rewrite(ast.getLeft(), a), ast.getOp(), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstCompare ast, T a) {
        return compare(rewrite(ast.getLeft(), a), ast.getOp(), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstArithm ast, T a) {
        return arithm(ast.getOp(), rewrite(ast.getOperands(), a));
    }

    @Override
    public AstExpr visit(AstMod ast, T a) {
        return mod(rewrite(ast.getDividend(), a), rewrite(ast.getDivisor(), a));
    }

    @Override
    public AstExpr visit(AstSum ast, T a) {
        return sum(rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstProduct ast, T a) {
        return product(rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstBoolArithm ast, T a) {
        return arithm(ast.getOp(), rewrite(ast.getOperands(), a));
    }

    @Override
    public AstExpr visit(AstDifference ast, T a) {
        return diff(rewrite(ast.getLeft(), a), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstIntersection ast, T a) {
        return inter(rewrite(ast.getLeft(), a), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstUnion ast, T a) {
        return union(rewrite(ast.getLeft(), a), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstMembership ast, T a) {
        return membership(rewrite(ast.getMember(), a), ast.getOp(), rewrite(ast.getSet(), a));
    }

    @Override
    public AstExpr visit(AstTernary ast, T a) {
        return ifThenElse(rewrite(ast.getAntecedent(), a), rewrite(ast.getConsequent(), a), rewrite(ast.getAlternative(), a));
    }

    @Override
    public AstExpr visit(AstIfThenElse ast, T a) {
        return ifThenElse(rewrite(ast.getAntecedent(), a), rewrite(ast.getConsequent(), a), rewrite(ast.getAlternative(), a));
    }

    @Override
    public AstExpr visit(AstDowncast ast, T a) {
        return downcast(rewrite(ast.getBase(), a), ast.getTarget());
    }

    @Override
    public AstExpr visit(AstUpcast ast, T a) {
        return upcast(rewrite(ast.getBase(), a), ast.getTarget());
    }

    @Override
    public AstExpr visit(AstLocal ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstQuantify ast, T a) {
        AstDecl[] decls = new AstDecl[ast.getDecls().length];
        for (int i = 0; i < decls.length; i++) {
            AstDecl decl = ast.getDecls()[i];
            AstLocal[] locals = new AstLocal[decl.getLocals().length];
            for (int j = 0; j < locals.length; j++) {
                locals[j] = (AstLocal) rewrite(decl.getLocals()[j], a);
            }
            decls[i] = decl(decl.isDisjoint(), locals, rewrite(decl.getBody(), a));
        }
        return quantify(ast.getQuantifier(), decls, rewrite(ast.getBody(), a));
    }

    @Override
    public AstExpr visit(AstLength ast, T a) {
        return length(rewrite(ast.getString(), a));
    }

    @Override
    public AstExpr visit(AstConcat ast, T a) {
        return concat(rewrite(ast.getLeft(), a), rewrite(ast.getRight(), a));
    }

    @Override
    public AstExpr visit(AstPrefix ast, T a) {
        return prefix(rewrite(ast.getPrefix(), a), rewrite(ast.getWord(), a));
    }

    @Override
    public AstExpr visit(AstSuffix ast, T a) {
        return suffix(rewrite(ast.getSuffix(), a), rewrite(ast.getWord(), a));
    }

    @Override
    public AstExpr visit(AstChildRelation ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstParentRelation ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstRefRelation ast, T a) {
        return ast;
    }

    @Override
    public AstExpr visit(AstDomainRestriction ast, T a) {
        return domainRestriction(rewrite(ast.getDomain(), a), rewrite(ast.getRelation(), a));
    }

    @Override
    public AstExpr visit(AstRangeRestriction ast, T a) {
        return rangeRestriction(rewrite(ast.getRelation(), a), rewrite(ast.getRange(), a));
    }

    @Override
    public AstExpr visit(AstInverse ast, T a) {
        return inverse(rewrite(ast.getRelation(), a));
    }

    @Override
    public AstExpr visit(AstTransitiveClosure ast, T a) {
        return transitiveClosure(rewrite(ast.getRelation(), a), ast.isReflexive());
    }

    @Override
    public AstExpr visit(AstConnected ast, T a) {
        AstSetExpr e = rewrite(ast.getRelation(), a);
        AstSetExpr n = rewrite(ast.getNodes(), a);
        return connected(n, e, ast.isDirected());
    }
}


text:
<!DOCTYPE html>
<html>
    <head>
        <link rel="search" type="application/opensearchdescription+xml" href="opensearch.xml">
    </head>
    <body></body>
</html>


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

<title>OnlineController.DeleteHabitEvents</title>
<meta name="date" content="2017-11-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.wsfmn.controller

Class OnlineController.DeleteHabitEvents

java.lang.Object

android.os.AsyncTask<HabitEvent,java.lang.Void,java.lang.Void>

com.wsfmn.controller.OnlineController.DeleteHabitEvents

Enclosing class:

OnlineController

public static class OnlineController.DeleteHabitEvents
extends android.os.AsyncTask<HabitEvent,java.lang.Void,java.lang.Void>

When GetHabits.execute(String... search_params) is called on a GetHabits object, this method
 will proceed if the device is connected to the internet and currently will return a
 HabitList object containing at most 10 Habit objects that match the search parameter.

 If the device is not connected to the internet this method fails silently and returns null

 Created by nmayne 11/07/17.

Nested Class Summary

Nested classes/interfaces inherited from class android.os.AsyncTask

android.os.AsyncTask.Status

Field Summary

Fields inherited from class android.os.AsyncTask

SERIAL_EXECUTOR, THREAD_POOL_EXECUTOR

Constructor Summary

Constructors

Constructor and Description

DeleteHabitEvents()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

protected java.lang.Void
doInBackground(HabitEvent... habitEvents)

Methods inherited from class android.os.AsyncTask

cancel, execute, execute, executeOnExecutor, get, get, getStatus, isCancelled, onCancelled, onCancelled, onPostExecute, onPreExecute, onProgressUpdate, publishProgress

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DeleteHabitEvents

public DeleteHabitEvents()

Method Detail

doInBackground

protected java.lang.Void doInBackground(HabitEvent... habitEvents)

Specified by:

doInBackground in class android.os.AsyncTask<HabitEvent,java.lang.Void,java.lang.Void>

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import * as React from 'react'
import {Switch} from 'react-native'
import {Cell} from 'react-native-tableview-simple'

type PropsType = {
	label: string,
	value: boolean,
	onChange: (val: boolean) => any,
}

export function CellToggle({value, onChange, label}: PropsType) {
	return (
		<Cell
			cellAccessoryView={<Switch onValueChange={onChange} value={value} />}
			title={label}
		/>
	)
}


text:
/* td represents the HTML tag for a table cell */
/* This affects the background color of a clicked-upon date in the calendar*/
td.select-highlight {
  background-color: #abffff
}

/* This affets the length of the Event Title text input bar */
input.eventtext {
  width: 240px
}

/* This affects the color of a private event on the calendar */
/*See calendar.client.controller.js line 126 for where 'private' comes from*/
  .fc-event.private {
  background-color: #ff0000;
  border: #aa0000;
}

/* This affects the color of a public event on the calendar */
/*See calendar.client.controller.js line 136 for where 'public' comes from*/
/* .public {
  background-color: #4545f0;
  border: #0b0b60;
}


text:
"""
Utilities to convert to and from base58.
"""

from .base_conversion import from_long, to_long, EncodingError
from .hash import double_sha256
from ..intbytes import iterbytes

BASE58_ALPHABET = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
BASE58_BASE = len(BASE58_ALPHABET)
BASE58_LOOKUP = dict((c, i) for i, c in enumerate(BASE58_ALPHABET))

def b2a_base58(s):
    """Convert binary to base58 using BASE58_ALPHABET. Like Bitcoin addresses."""
    v, prefix = to_long(256, lambda x: x, iterbytes(s))
    s = from_long(v, prefix, BASE58_BASE, lambda v: BASE58_ALPHABET[v])
    return s.decode("utf8")

def a2b_base58(s):
    """Convert base58 to binary using BASE58_ALPHABET."""
    v, prefix = to_long(BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8"))
    return from_long(v, prefix, 256, lambda x: x)

def b2a_hashed_base58(data):
    """
    A "hashed_base58" structure is a base58 integer (which looks like a string)
    with four bytes of hash data at the end. Bitcoin does this in several places,
    including Bitcoin addresses.

    This function turns data (of type "bytes") into its hashed_base58 equivalent.
    """
    return b2a_base58(data + double_sha256(data)[:4])

def a2b_hashed_base58(s):
    """
    If the passed string is hashed_base58, return the binary data.
    Otherwise raises an EncodingError.
    """
    data = a2b_base58(s)
    data, the_hash = data[:-4], data[-4:]
    if double_sha256(data)[:4] == the_hash:
        return data
    raise EncodingError("hashed base58 has bad checksum %s" % s)

def is_hashed_base58_valid(base58):
    """Return True if and only if base58 is valid hashed_base58."""
    try:
        a2b_hashed_base58(base58)
    except EncodingError:
        return False
    return True

"""
The MIT License (MIT)

Copyright (c) 2013 by Richard Kiss

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


text:
package syscerts

import (
	"crypto/x509"
	"io/ioutil"
)

// Possible directories with certificate files; stop after successfully
// reading at least one file from a directory.
var certDirectories = []string{
	"/etc/ssl/certs",               // SLES10/SLES11, https://golang.org/issue/12139
	"/system/etc/security/cacerts", // Android
}

func initSystemRoots() {
	roots := x509.NewCertPool()
	for _, file := range certFiles {
		data, err := ioutil.ReadFile(file)
		if err == nil {
			roots.AppendCertsFromPEM(data)
			systemRoots = roots
			return
		}
	}

	for _, directory := range certDirectories {
		fis, err := ioutil.ReadDir(directory)
		if err != nil {
			continue
		}
		rootsAdded := false
		for _, fi := range fis {
			data, err := ioutil.ReadFile(directory + "/" + fi.Name())
			if err == nil && roots.AppendCertsFromPEM(data) {
				rootsAdded = true
			}
		}
		if rootsAdded {
			systemRoots = roots
			return
		}
	}

	// All of the files failed to load. systemRoots will be nil which will
	// trigger a specific error at verification time.
}


text:
. ../config.init
. ./localConfig.init
export PYTHONPATH=$PYTHONPATH:$root_path:$root_path/$process_id
echo $PYTHONPATH
export train_path=./dataPreprocess/used/train
python  ./experiments/nmt/train.py  --proto=prototype_encdec_state "prefix='$train_path/encdec-50_',seqlen=50,sort_k_batches=20"
# python  ./experiments/nmt/train.py --proto=prototype_search_state "prefix='$train_path/search_',seqlen=50,sort_k_batches=20"


text:
Bump versions for package.json, bower.json, and git

![ss](https://raw.githubusercontent.com/evanlucas/bumpit/master/ss.png)

## Install

```bash
$ npm install -g @evanlucas/bumpit
```

**Note: This is very ugly and needs to be re-written and be async only**

## Author

Evan Lucas

## License

MIT (See `LICENSE` for more info)


text:
layout: post
title: Sexy Lexi and Alexis May get gangbanged and jizzed over in this hotel party
titleinfo: pornvd
desc: Watch Sexy Lexi and Alexis May get gangbanged and jizzed over in this hotel party. Pornhub is the ultimate xxx porn and sex site.
---

Sexy Lexi and Alexis May get gangbanged and jizzed over in this hotel party

Watch Sexy Lexi and Alexis May get gangbanged and jizzed over in this hotel party. Pornhub is the ultimate xxx porn and sex site.


text:
<?php

namespace Torchbox\Thankq\Services\Contact;

use Torchbox\Thankq\Exception\ThankqApiException;
use Torchbox\Thankq\Services\ThankqClient;
use Torchbox\Thankq\Services\Validation;
use Torchbox\Thankq\Exception\ApiClassException;
use Torchbox\Thankq\Exception\ValidationException;

/**
 * Class Base
 * Base for performing 'contact' operations on the API - contact data is the
 * main data held for a member in the CRM.
 *
 * @package Torchbox\Thankq\Services\Contact
 */
abstract class Base {

  /** @var ThankqClient **/
  protected $client;

  /** @var Validation $validation **/
  protected $validation;

  /**
   * Contact constructor.
   * @param ThankqClient $client
   * @param Validation $validation
   */
  public function __construct(ThankqClient $client, Validation $validation) {
    $this->client = $client;
    $this->validation = $validation;
  }

  /**
   * @var array Incoming field data keys associated with their esit class,
   * method and validation method(s).
   */
  protected $field_map = [

    /**
     * esitWScontact
     */
    // @TODO: Check title is one of allowed from getLookups
    'crm_contact__title' => [
      'class' => 'esitWScontact',
      'method' => 'setTitle',
      'validation' => ['checkIsAllowedNamePrefix'],
    ],
    'crm_contact__first_name' => [
      'class' => 'esitWScontact',
      'method' => 'setFirstname',
      'validation' => [],
    ],

    // Secondname = surname, fyi
    // @TODO: Min 2 chars
    'crm_contact__second_name' => [
      'class' => 'esitWScontact',
      'method' => 'setKeyname',
      'validation' => [],
    ],

    /* Currently unused by us:
    'crm_contact__initial' => [
      'class' => 'esitWScontact',
      'method' => 'setOtherInitial',
      'validation' => [],
    ],
    // @TODO: What is this??
    'crm_contact__post_nominal' => [
      'class' => 'esitWScontact',
      'method' => 'setPostNominal',
      'validation' => [],
    ],

    */

    /**
     * esitWScontactAddress
     */

    'mail' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setEmailAddress',
      'validation' => [],
    ],
    'crm_contact__address_1' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setAddressLine1',
      'validation' => ['checkNoCommas'],
    ],
    // Basically there's nowhere for address_2 to go in thankq
    // - we merge address_2 into address_1 in $this->preProcessFieldData()
    'crm_contact__address_2' => [
      'validation' => ['checkNoCommas'],
    ],

    'crm_contact__address_town' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setAddressLine3',
      'validation' => [],
    ],

    'crm_contact__address_county' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setAddressLine4',
      'validation' => [],
    ],
    'crm_contact__postcode' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setPostcode',
      'validation' => [],
    ],
    'crm_contact__phone_daytime' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setDayTelephone',
      'validation' => [],
    ],
    'crm_contact__phone_evening' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setEveningTelephone',
      'validation' => [],
    ],
    'crm_contact__phone_mobile' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setMobileNumber',
      'validation' => [],
    ],

    /* Currently unused by us:
    'crm_contact__country' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setCountry',
      'validation' => [],
    ],
    'crm_contact__website' => [
      'class' => 'esitWScontactAddress',
      'method' => 'setWebsite',
      'validation' => [],
    ],
    */

    /**
     * esitWScontactAttribute
     */

    'crm_contact__dob' => [
      'class' => 'esitWScontactAttribute',
      'method' => 'setDateOfBirth',
      // Must be datetime object \DateTime
      'validation' => ['checkIsDatetimeObject'],
    ],
    'crm_contact__source' => [
      'class' => 'esitWScontactAttribute',
      'method' => 'setSource',
      'validation' => [],
    ],

    'crm_contact__organisation' => [],

    // @TODO Default is individual. Set to other value if organisation provided.
    'crm_contact__contact_type' => [
      'class' => 'esitWScontactAttribute',
      'method' => 'setContactType',
      'validation' => [],
    ],

    /* Unused:
    // Gender is automatically determined by the CRM using the name prefix
    'gender' => [      'class' => 'esitWScontactAttribute',
      'method' => 'setGender',
      'validation' => [,
    ],
    'marital_status' => [      'class' => 'esitWScontactAttribute',
      'method' => 'setGender',
      'validation' => [,
    ],
    */

    /**
     * esitWScontactDataProtection
     */

    'crm_contact__do_not_contact' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setDoNotContact',
    ],
    'crm_contact__do_not_mail' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setDoNotMail',
      'validation' => [],
    ],
    'crm_contact__do_not_phone' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setDoNotPhone',
    ],
    'crm_contact__do_not_email' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setDoNotEmail',
    ],
    'crm_contact__do_not_sms' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setDoNotSMS',
    ],

    'crm_contact__mail_third_party' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setMailThirdParty',
    ],
    'crm_contact__email_third_party' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setEmailThirdParty',
    ],
    'crm_contact__phone_third_party' => [
      'class' => 'esitWScontactDataProtection',
      'method' => 'setPhoneThirdParty',
    ],
/*
    'dm_email_opt_in' => [      'class' => 'esitWScontactDataProtection',
      'method' => 'setDmEmailOptIn',
    ),
    'dm_mail_opt_in' => [      'class' => 'esitWScontactDataProtection',
      'method' => 'setDmMailOptIn',
    ),
*/

  ];

  /**
   * Retrieve the fields map - useful for dev, knowing what field IDs the
   * this library should expect.
   * @param bool $field_defs_only
   * @return array
   */
  public function getFieldMap($field_defs_only = FALSE) {
   return $field_defs_only ? array_keys($this->field_map) : $this->field_map;
  }

  /**
   * @param $field_map
   */
  public function setFieldMap($field_map) {
    $this->field_map = $field_map;
  }

  /**
   * Publicly accessible middleman to preprocess and validation field data. The
   * idea is to be able to use this method to prepare the input data for thankq,
   * (for example such processing as merge address_2 into address_1), THEN
   * validate. Keeping these functions separate from actual data insert/update
   * operations means we can queue the already prepared and validated data in
   * externally if needs be.
   * @param array $field_data
   * @return array
   */
  public function checkFieldData(array $field_data) {
    $this->preProcessFieldData($field_data);
    $this->validateFieldData($field_data);
    return $field_data;
  }
  /**
   * Some input field data will need adjusting before validation and
   * @param $field_data
   */
  protected function preProcessFieldData(array &$field_data) {

    /**
     * Do things to the input data array before any validation and API calls
     * @TODO, remember address_2 input field map is an empty array!
     * @TODO Contact type, address type, where does organisation name go?
     * @TODO 'Source' is accounted for, but not 'source other' on API spreadsheet
     * @TODO Do the work surrounding initials if first name is of min length
     *
     */

    // There is no storage for address2 in Thankq - Merge add2 into 1, separate with newline.
    if (!empty($field_data['crm_contact__address_1']) && !empty(trim($field_data['crm_contact__address_2']))) {
      $field_data['crm_contact__address_1'] = $field_data['crm_contact__address_1'] . "\n" . $field_data['crm_contact__address_2'];
      unset($field_data['crm_contact__address_2']);
    }

  }

  /**
   * Delegate input fields to validation functions as declared in
   * $this->field_map above. We should be able to execute this from outside
   * the library.
   *
   * @param array $field_data
   * @return array $field_data
   * @throws \Torchbox\Thankq\Exception\ApiClassException
   */
  protected function validateFieldData(array &$field_data) {
    $result = NULL;
    foreach ($field_data as $field_name => $value) {
      if (array_key_exists($field_name, $this->field_map)) {
        $validation_functions = !empty($this->field_map[$field_name]['validation']) ? $this->field_map[$field_name]['validation'] : array();
        foreach ($validation_functions as $function) {

          // Call corresponding validation method from Validation Class.
          if (method_exists($this->validation, $function) && is_callable(array($this->validation, $function))) {
            call_user_func(array($this->validation, $function), $field_name, $value);
          }
          else {
            throw new ApiClassException('Method ' . $function . ' does not exist or is not callable on class Torchbox\\Thankq\\Validation.');
          }
        }
      }
    }
    // If we reach here without exception then flag validated
    $field_data['crm_validated'] = TRUE;
  }

  /**
   * Set data for insertion on the appropriate arguments.
   *
   * @param array $field_data
   * @throws \Torchbox\Thankq\Exception\ThankqApiException
   */
  protected function setContactData(array $field_data) {

    foreach ($field_data as $field_name => $value) {
      // Value we're setting on a field may be a boolean - check not null instead.
      if (array_key_exists($field_name, $this->field_map) && !is_null($field_data[$field_name])) {
        // convert the classname in array to variable
        $classname = $this->field_map[$field_name]['class'];
        // Variable variable (usually double $$ for procedural stuff).
        $class = $this->$classname;

        if (method_exists($class, $this->field_map[$field_name]['method']) && is_callable(array($class, $this->field_map[$field_name]['method']))) {
          //error_log($class . ' ' . $field_map[$field_name]['method']);
          call_user_func(array($class, $this->field_map[$field_name]['method']), $value);
        } else {
          throw new ApiClassException('Method ' . $this->field_map[$field_name]['method'] . ' does not exist or is not callable on API class ' . $classname . '.');
        }

      }
    }
    return $this;
  }

}


text:
'use strict';

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

/**
 * OpenId Connect Provider details.
 *
 * @extends models['Resource']
 */
class OpenidConnectProviderContract extends models['Resource'] {
  /**
   * Create a OpenidConnectProviderContract.
   * @member {string} displayName User-friendly OpenID Connect Provider name.
   * @member {string} [description] User-friendly description of OpenID Connect
   * Provider.
   * @member {string} metadataEndpoint Metadata endpoint URI.
   * @member {string} clientId Client ID of developer console which is the
   * client application.
   * @member {string} [clientSecret] Client Secret of developer console which
   * is the client application.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of OpenidConnectProviderContract
   *
   * @returns {object} metadata of OpenidConnectProviderContract
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'OpenidConnectProviderContract',
      type: {
        name: 'Composite',
        className: 'OpenidConnectProviderContract',
        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'
            }
          },
          displayName: {
            required: true,
            serializedName: 'properties.displayName',
            constraints: {
              MaxLength: 50
            },
            type: {
              name: 'String'
            }
          },
          description: {
            required: false,
            serializedName: 'properties.description',
            type: {
              name: 'String'
            }
          },
          metadataEndpoint: {
            required: true,
            serializedName: 'properties.metadataEndpoint',
            type: {
              name: 'String'
            }
          },
          clientId: {
            required: true,
            serializedName: 'properties.clientId',
            type: {
              name: 'String'
            }
          },
          clientSecret: {
            required: false,
            serializedName: 'properties.clientSecret',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = OpenidConnectProviderContract;


text:
package com.fangxu.dota2helper.ui.adapter;

import android.content.Context;

import com.fangxu.dota2helper.callback.WatchedVideoSelectCountCallback;
import com.youku.service.download.DownloadInfo;
import com.youku.service.download.DownloadManager;

import java.util.Iterator;

/**
 * Created by dear33 on 2016/7/27.
 */
public abstract class BaseCacheVideoAdapter extends BaseVideoListAdapter<DownloadInfo> {

    protected abstract void deleteCache(DownloadInfo downloadInfo);

    public BaseCacheVideoAdapter(Context context) {
        super(context);
    }

    public BaseCacheVideoAdapter(Context context, WatchedVideoSelectCountCallback countCallback) {
        super(context, countCallback);
    }

    @Override
    public int deleteSelected() {
        Iterator<DownloadInfo> iterator = mData.iterator();
        while (iterator.hasNext()) {
            DownloadInfo video = iterator.next();
            String key = video.videoid;
            if (mSelectedVideos.contains(key)) {
                iterator.remove();
                deleteCache(video);
            }
        }
        int deleteCount = mSelectedVideos.size();
        mSelectedVideos.clear();
        notifyDataSetChanged();
        notifyVideoSelectCount();
        return deleteCount;
    }

    @Override
    public void selectAll() {
        if (mSelectedVideos.isEmpty()) {
            for (DownloadInfo video : mData) {
                mSelectedVideos.add(video.videoid);
            }
        } else {
            if (mSelectedVideos.size() == mData.size()) {
                mSelectedVideos.clear();
            } else {
                for (DownloadInfo video : mData) {
                    mSelectedVideos.add(video.videoid);
                }
            }
        }
        notifyDataSetChanged();
        notifyVideoSelectCount();
    }

    @Override
    public String getYkVid(int position) {
        return getItem(position).videoid;
    }
}


text:
  Saint-Bauzile est
       un village
       localisé dans le département de Lozère en Languedoc-Roussillon. Elle comptait 545 habitants en 2008.

Le nombre de logements, à Saint-Bauzile, se décomposait en 2011 en 19 appartements et 284 maisons soit
 un marché relativement équilibré.

Saint-Bauzile est localisé à seulement 4 km de Mende, les étudiants qui voudrons se loger à moindre coût pourront envisager de prendre un appartement à Saint-Bauzile. Saint-Bauzile est aussi un bon placement locatif a cause de sa proximité de Mende et de ses Universités. Il sera aisé de trouver un appartement à vendre.

La ville compte de nombreux  équipements, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et trois boucles de randonnée.

Si vous pensez demenager à Saint-Bauzile, vous pourrez aisément trouver une maison à vendre.

À Saint-Bauzile, la valeur moyenne à la vente d'un appartement s'évalue à 2 218 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 681 € du m². À la location le prix moyen se situe à 0 € du m² par mois.

À proximité de Saint-Bauzile sont localisées les villes de
Badaroux à 7 km, 884 habitants,
Sainte-Hélène située à 9 km, 65 habitants,
Le Born située à 9 km, 150 habitants,
Cultures localisée à 9 km, 120 habitants,
Brenoux située à 2 km, 284 habitants,
Pierrefiche localisée à 9 km, 160 habitants,
 entre autres. De plus, Saint-Bauzile est située à seulement quatre km de Mende.


text:
package goja.initialize;

/**
 * <p> </p>
 *
 * @author sog
 * @version 1.0
 * @since JDK 1.6
 */
public final class GojaBootVersion {

    private GojaBootVersion() {
    }

    /**
     * Return the full version string of the present Goja Boot codebase, or {@code null}
     * if it cannot be determined.
     * @return the version of Goja Boot or {@code null}
     * @see Package#getImplementationVersion()
     */
    public static String getVersion() {
        Package pkg = GojaBootVersion.class.getPackage();
        return (pkg != null ? pkg.getImplementationVersion() : null);
    }

}


text:
class AddAwardedAtAndDraftExpToCourseExperiencePointsRecords < ActiveRecord::Migration[4.2]
  def change
    add_column :course_experience_points_records, :draft_points_awarded, :integer
    add_column :course_experience_points_records, :awarded_at, :datetime
    add_column :course_experience_points_records, :awarder_id, :integer,
               foreign_key: { references: :users }

    Course::Assessment::Submission.joins(:experience_points_record).
      where(workflow_state: ['attempting', 'submitted', 'graded']).find_each do |submission|
      # Shift exp to draft exp
      points_awarded = submission.points_awarded
      submission.experience_points_record.update_columns(
        draft_points_awarded: points_awarded, points_awarded: nil
      )
    end

    Course::Assessment::Submission.joins(:experience_points_record).
      where(workflow_state: 'published').find_each do |submission|
      # Update awarded_at and awarder_id
      awarded_at = submission.experience_points_record.updated_at
      awarder_id = submission.experience_points_record.updater_id
      submission.experience_points_record.update_columns(
        awarded_at: awarded_at, awarder_id: awarder_id
      )
    end
  end
end


text:
This practical covers:

* Implementing (a simplified) Baker's algorithm for clone detection
* Applying clone detection to identify clones, and refactoring to remove them
* Improving on Baker's algorithm with some practical optimisations

## Building the clone detection tool

Your first task is to complete the `clones` tool so that it implements Baker's algorithm, which was discussed in the lectures. The code in this repository contains an executable which can be invoked using `vado clones detect PROJECT`. Run `vado clones help` for more information.

The sample projects in the `data` folder can be used to test the clones tool. To get started, create a straightforward code clone by duplicating `data/hello_world/hello_world.rb` in a new file `data/hello_world/goodbye_world.rb`. Replace all instances of "Hello" with "Goodbye" in `data/hello_world/goodbye_world.rb`

If you run, say, `vado clones detect hello_world` you'll notice that the `clones` tool doesn't do much yet:

```
hello_world.rb
--------------

goodbye_world.rb
--------------
```

### Computing common fragments

A simple yet reasonably effective way to identify code clones is to locate identical parts of two source files. For the purposes of this practical, we'll use the term fragment to mean "a part of a source file" and we'll restrict ourselves to thinking about breaking source files down by line. To identify a fragment, we'll use the notation `hello_world.rb:2..4` which can be read as "lines 2 to 4 of hello_world.rb". We'll represent a fragment as an array of strings, where each member of the array is a line of source code. So, "hello_world.rb:2..4" will be equivalent to:

```ruby
[
  "  class HelloWorld",
  "    attr_reader :name",
  ""
]
```

Your first task is to implement a method that compares two pieces of source code and identifies fragments that they have in common. Note that, for now, this method will return only one common fragment (i.e., an array of strings) and not an array of all common fragments (i.e., not an array of array of strings). Some test cases have been provided to explain the intended functionality of the common fragments algorithm. Use `vado bundle exec rspec` to run the test cases. The first time that you run the tests, you will see several failures:

```sh
> vado bundle exec rspec
...
Failed examples:

rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:6 # Subjects::Source common_fragment_with should find first fragment of appropriate length
rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:13 # Subjects::Source common_fragment_with should find first fragment of appropriate length when match occurs in middle of sources
rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:20 # Subjects::Source common_fragment_with should return nil when there is no common fragment
rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:27 # Subjects::Source common_fragment_with should find fragments when length is larger than 1
rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:34 # Subjects::Source common_fragment_with should return nil when there is no fragment of the appropriate length
```

You can examine the expected behaviour of the common fragment method by looking at the failures and at the test case source code in `./habitable_programs/tools/common/spec/subjects/source_spec.rb`. Your implementation of the common fragment algorithm should be specified in the `common_fragment_with` method of `./habitable_programs/tools/common/lib/subjects/source.rb`.

### Computing longest common fragments

Next, implement the `longest_common_fragment_with` method to locate common fragments with at least as many lines as any other common fragment. Once again, there are some test cases that you can use to get started. In `./habitable_programs/tools/common/spec/subjects/source_spec` change the `xdescribe` on line 43 to `describe` and run `vado bundle exec rspec`. You will see some new failures:

```sh
> vado bundle exec rspec
...
rspec ./habitable_programs/tools/common/spec/subjects/source_spec.rb:44 # Subjects::Source longest_common_fragment_with should find longest common fragment between two sources
```

Your implementation of the longest common fragment algorithm should be specified in the `longest_common_fragment_with` method of `./habitable_programs/tools/common/lib/subjects/source.rb`. Hint: a recursive solution will change the method signature to `longest_common_fragment_with(other_source, longest_yet = [])`.

Once the `longest_common_fragment_with` method is complete, you can start using the `clones` tool to identify code clones within a project. For example, running `vado clones detect hello_world` will produce some useful output:

```ruby
# goodbye_world.rb
# ----------------
# hello_world.rb:2..9 matches 2..9:
  attr_reader :name

  def initialize(name = "world")
    @name = name
  end

  def run

# hello_world.rb
# --------------
# goodbye_world.rb:2..9 matches 2..9:
  attr_reader :name

  def initialize(name = "world")
    @name = name
  end

  def run
```

## Improving the clone detection tool

When running the initial implementation of `clones` on more realistic projects, it becomes apparent that it often reports false positives (i.e., fragments of text that are not code clones, or that are not interesting code clones). For example, running `vado clones detect adamantium` will return lots of fragments that return comments and common Ruby keywords. Let's fix this...

The most reliable way to remove comments from Ruby source code is to use the Ruby parser to build an AST (which strips away comments by default) and then to use the unparser to pretty print the AST. The `Source` file provides a `normalized_source` method that strips comments using these technique. To make use of this, simply change line 20 of `./habitable_programs/tools/clones/lib/clone_detector.rb` to read: `.flat_map { |other_file| clones_between(file.normalized_source, other_file.normalized_source) }`.

The `normalized_source` method will also remove indentation from the source code, so that identical fragments that appear at different levels of nesting might also be detected.

Once the `clones` tool ignores comments (and indentation), it will identify fewer clones for adamantium:

```sh
> vado clones detect adamantium
adamantium/class_methods.rb
---------------------------
adamantium/mutable.rb:7..10 matches 4..7:
    end
  end
end
adamantium/module_methods.rb:26..29 matches 4..7:
    end
  end
end
adamantium/freezer.rb:53..56 matches 4..7:
    end
  end
end
adamantium.rb:24..26 matches 4..6:
    end
  end
adamantium/version.rb:0..1 matches 0..1:
module Adamantium

adamantium/freezer.rb
---------------------
adamantium.rb:23..26 matches 52..55:
      end
    end
  end
adamantium/mutable.rb:7..10 matches 53..56:
    end
  end
end
adamantium/module_methods.rb:26..29 matches 53..56:
    end
  end
end
adamantium/class_methods.rb:4..7 matches 53..56:
    end
  end
end
adamantium/version.rb:0..1 matches 0..1:
module Adamantium

adamantium/module_methods.rb
----------------------------
adamantium/mutable.rb:7..10 matches 26..29:
    end
  end
end
adamantium/freezer.rb:53..56 matches 26..29:
    end
  end
end
adamantium/class_methods.rb:4..7 matches 26..29:
    end
  end
end
adamantium.rb:12..14 matches 22..24:
      end
    end
adamantium/version.rb:0..1 matches 0..1:
module Adamantium

adamantium/mutable.rb
---------------------
adamantium/module_methods.rb:26..29 matches 7..10:
    end
  end
end
adamantium/freezer.rb:53..56 matches 7..10:
    end
  end
end
adamantium/class_methods.rb:4..7 matches 7..10:
    end
  end
end
adamantium.rb:24..26 matches 7..9:
    end
  end
adamantium/version.rb:0..1 matches 0..1:
module Adamantium

adamantium/version.rb
---------------------
adamantium.rb:2..3 matches 0..1:
module Adamantium
adamantium/mutable.rb:0..1 matches 0..1:
module Adamantium
adamantium/module_methods.rb:0..1 matches 0..1:
module Adamantium
adamantium/freezer.rb:0..1 matches 0..1:
module Adamantium
adamantium/class_methods.rb:0..1 matches 0..1:
module Adamantium

adamantium.rb
-------------
adamantium/freezer.rb:52..55 matches 23..26:
      end
    end
  end
adamantium/mutable.rb:7..9 matches 24..26:
    end
  end
adamantium/module_methods.rb:22..24 matches 12..14:
      end
    end
adamantium/class_methods.rb:4..6 matches 24..26:
    end
  end
adamantium/version.rb:0..1 matches 2..3:
module Adamantium
```

Removing uninteresting code clones (e.g., a series of `end` keywords) is a bit tricker, and is your next task. Change the implementation of Source to ignore fragments whose lines only contain the `end`, `class`, `module` and `self` keywords. Once the `clones` tool ignores these uninteresting fragments, it will identify fewer clones for adamantium:

```sh
> vado clones detect adamantium
adamantium/class_methods.rb
---------------------------

adamantium/freezer.rb
---------------------
adamantium/module_methods.rb:8..9 matches 7..8:
      else

adamantium/module_methods.rb
----------------------------
adamantium.rb:4..5 matches 2..3:
    def freezer
adamantium/freezer.rb:7..8 matches 8..9:
      else

adamantium/mutable.rb
---------------------

adamantium/version.rb
---------------------

adamantium.rb
-------------
adamantium/module_methods.rb:2..3 matches 4..5:
    def freezer
```

Note that the remaining clones are only one line long. One-line clones are really interesting. Let's fix this...

Change `longest_common_fragment` (and its tests) to take an additional `threshold (int)` parameter. The new version of `longest_common_fragment_with` must not return any fragment that has fewer lines than the threshold parameter (and can instead return `[]`). Hint: the recursive solution results in the method signature `longest_common_fragment_with(other_source, threshold = 2, longest_yet = [])`

Once this change has been made, running `clones` on adamantium will correctly report that there are no (interesting) code clones. Ensure that this latest version of `clones` can still detect the code clone that you introduced at the start of the practical, in `goodbye_world.rb`.

## Bonus Exercise: Making the clone detection tool even better

Currently the `clones` tool has several deficiencies. Address the most obvious of these by:

### Listing **all** clones between every pair of files

Start by changing CloneDetector#clones_between to:

```ruby
def clones_between(source, other_source)
  source.all_common_fragments_with(other_source).map do |common_fragment|
    Clone.new(source, other_source, longest_common_fragment)
  end
end
```

Now implement `all_common_fragments_with` on Source. An outstanding implementation of this method will ensure that the results contain no overlapping fragments. For example, if `hello_world.rb:5-20` is a fragment, then `hello_world.rb:6-19` should not be returned (because the latter is wholly contained in the former).

### Implementing the **parameterised** version of Baker's algorithm

Preprocess the AST to replace any concrete module, class, method, attribute and variable names with a constant (e.g., `module Measurement` -> `module M` and `module Detection` -> `module D`). This will allow clone detection for semantically equivalent but syntactically different fragments.

Start by adding a new method SourceFile, say `parameterized_source`, that performs this preprocessing. Then, change line 20 of `./habitable_programs/tools/clones/lib/clone_detector.rb` to read: `.flat_map { |other_file| clones_between(file.parameterized_source, other_file.parameterized_source) }`.


text:
<?php

namespace App\MainBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @MongoDB\EmbeddedDocument()
 */
class OrderContent
{
    /**
     * @MongoDB\Id(type="int")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $uniqId;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $id;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $title;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $image;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $uri;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $contentTypeName;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details", "list"})
     * @var float
     */
    protected $count;

    /**
     * @MongoDB\Field(type="float")
     * @Groups({"details", "list"})
     * @var float
     */
    protected $price;

    /**
     * @MongoDB\Field(type="collection", nullable=true)
     * @Groups({"details"})
     * @var array
     */
    protected $parameters = [];

    /**
     * @MongoDB\Field(type="collection", nullable=true)
     * @Groups({"details"})
     * @var array
     */
    protected $files = [];

    /**
     * @MongoDB\Field(type="hash")
     * @Groups({"details", "list"})
     * @var array
     */
    protected $options;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $currency;

    /**
     * @MongoDB\Field(type="boolean")
     * @Groups({"details", "list"})
     * @var bool
     */
    protected $deleted;

    /**
     * Get uniqId
     * @return int
     */
    public function getUniqId()
    {
        return $this->uniqId;
    }

    /**
     * Get id
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set id
     * @param int $id
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * Set title
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }

    /**
     * Get title
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set image
     * @param string $image
     * @return $this
     */
    public function setImage($image)
    {
        $this->image = $image;
        return $this;
    }

    /**
     * Get image
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set uri
     * @param string $uri
     * @return $this
     */
    public function setUri($uri)
    {
        $this->uri = $uri;
        return $this;
    }

    /**
     * Get uri
     * @return string
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * Set contentTypeName
     * @param string $contentTypeName
     * @return $this
     */
    public function setContentTypeName($contentTypeName)
    {
        $this->contentTypeName = $contentTypeName;
        return $this;
    }

    /**
     * Get contentTypeName
     * @return string
     */
    public function getContentTypeName()
    {
        return $this->contentTypeName;
    }

    /**
     * Set count
     * @param float $count
     * @return $this
     */
    public function setCount($count)
    {
        $this->count = $count;
        return $this;
    }

    /**
     * Get count
     * @return float
     */
    public function getCount()
    {
        return $this->count;
    }

    /**
     * Set price
     * @param float $price
     * @param int $currencyRate
     * @return $this
     */
    public function setPrice($price, $currencyRate = 1)
    {
        $this->price = round(floatval($price) / $currencyRate, 2);
        return $this;
    }

    /**
     * @param int $value
     * @return $this
     */
    public function incrementCount($value)
    {
        $this->count += (int) $value;
        return $this;
    }

    /**
     * Get price
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set parameters
     * @param array $parameters
     * @param int $currencyRate
     * @return $this
     */
    public function setParameters($parameters, $currencyRate = 1)
    {
        if (!empty($parameters) && $currencyRate !== 1) {
            foreach ($parameters as &$parameter) {
                $parameter['price'] = round($parameter['price'] / $currencyRate, 2);
            }
        }
        $this->parameters = $parameters;
        return $this;
    }

    /**
     * Get parameters
     * @return array
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * Add file
     * @param array $files
     * @return $this
     */
    public function setFiles($files)
    {
        $this->files = $files;
        return $this;
    }

    /**
     * Get files
     * @return array
     */
    public function getFiles()
    {
        return $this->files;
    }

    /**
     * Add file
     * @param FileDocument $fileDocument
     * @return $this
     */
    public function addFile(FileDocument $fileDocument)
    {
        $this->files[] = $fileDocument->getRecordData();
        return $this;
    }

    /**
     * Set currency
     *
     * @param string $currency
     * @return $this
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
        return $this;
    }

    /**
     * Get currency
     *
     * @return string
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * Set options
     *
     * @param array $options
     * @return $this
     */
    public function setOptions($options)
    {
        $this->options = $options;
        return $this;
    }

    /**
     * Get options
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @param $key
     * @param string $default
     * @return mixed|string
     */
    public function getOptionValue($key, $default = '')
    {
        return isset($this->options[$key])
            ? $this->options[$key]
            : $default;
    }

    /**
     * @param $key
     * @param $value
     * @return $this
     */
    public function setOptionValue($key, $value)
    {
        $options = $this->getOptions();
        $options[$key] = $value;
        $this->setOptions($options);
        return $this;
    }

    /**
     * Get parameters price
     * @return float|int
     */
    public function getParametersPrice()
    {
        $parametersPrice = 0;
        $parameters = $this->getParameters();
        foreach ($parameters as $parameter) {
            if (!empty($parameter['price'])) {
                $parametersPrice += $parameter['price'];
            }
        }
        $parametersPrice *= $this->getCount();
        return $parametersPrice;
    }

    /**
     * Get price total
     * @return float
     */
    public function getPriceTotal()
    {
        $priceTotal = $this->getPrice() * $this->getCount();
        $parametersPrice = $this->getParametersPrice();
        return $priceTotal + $parametersPrice;
    }

    /**
     * Get parameters string
     * @return string
     */
    public function getParametersString()
    {
        return self::getParametersStrFromArray($this->getParameters());
    }

    /**
     * @param array $parameters
     * @param string $currency
     * @return string
     */
    public static function getParametersStrFromArray($parameters = [], $currency = '')
    {
        $outputArr = [];
        foreach ($parameters as $parameter) {
            $str = '';
            if ($parameter['name']) {
                $str = $parameter['name'];
            }
            if ($parameter['value']) {
                $str .= ": {$parameter['value']}";
            }
            if (!empty($parameter['price'])) {
                $str .= $currency
                    ? " ({$parameter['price']} {$currency})"
                    : " ({$parameter['price']})";
            }
            array_push($outputArr, $str);
        }
        return implode(', ', $outputArr);
    }

    /**
     * Get files string
     * @return string
     */
    public function getFilesString()
    {
        return self::getFilesStrFromArray($this->getFiles());
    }

    /**
     * Get files string from array
     * @param array|null $files
     * @return string
     */
    public static function getFilesStrFromArray($files = null)
    {
        if (!$files) {
            return '';
        }
        $outputArr = [];
        foreach ($files as $file) {
            if ($file instanceof FileDocument) {
                /** @var FileDocument $file */
                $str = $file->getTitle() . '.' . $file->getExtension();
            } else {
                $str = $file['title'] . '.' . $file['extension'];
            }
            array_push($outputArr, $str);
        }
        return implode(', ', $outputArr);
    }

    /**
     * @param $key
     * @param string $default
     * @return mixed|string
     */
    public function getByKey($key, $default = '')
    {
        if (method_exists($this, 'get' . $key)) {
            return call_user_func([$this, 'get' . $key]);
        }
        return $default;
    }

    /**
     * To array
     * @return array
     */
    public function toArray()
    {
        return [
            'id' => $this->getId(),
            'title' => $this->getTitle(),
            'count' => $this->getCount(),
            'price' => $this->getPrice(),
            'priceTotal' => $this->getPriceTotal(),
            'image' => $this->getImage(),
            'uri' => $this->getUri(),
            'contentTypeName' => $this->getContentTypeName(),
            'parameters' => $this->getParameters(),
            'files' => $this->getFiles(),
            'parametersString' => '',
            'filesString' => $this->getFilesString()
        ];
    }

    /**
     * From array
     * @param array $data
     * @return $this
     */
    public function fromArray($data)
    {
        $this
            ->setId($data['id'])
            ->setTitle($data['title'])
            ->setCount($data['count'])
            ->setPrice($data['price'])
            ->setImage($data['image'])
            ->setUri($data['uri'])
            ->setContentTypeName($data['contentTypeName'])
            ->setParameters($data['parameters'])
            ->setFiles($data['files']);
        return $this;
    }

    /**
     * @param OrderContent $object
     * @param float|int $currencyRate
     * @return $this
     */
    public function cloneFrom($object, $currencyRate = 1)
    {
        $this
            ->setId($object->getId())
            ->setTitle($object->getTitle())
            ->setCount($object->getCount())
            ->setPrice($object->getPrice(), $currencyRate)
            ->setImage($object->getImage())
            ->setUri($object->getUri())
            ->setContentTypeName($object->getContentTypeName())
            ->setParameters($object->getParameters(), $currencyRate)
            ->setFiles($object->getFiles());

        return $this;
    }

    /**
     * @return bool
     */
    public function getDeleted()
    {
        return $this->deleted;
    }

    /**
     * @param bool $deleted
     * @return OrderContent
     */
    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;
        return $this;
    }
}


text:
A basic Node.js media server

This programs serves the audio, video and images in a directory in a barebones
keyboard-accessible media interface.

This was created as an example for a media server discovery project but may
be useful for people wanting to access media on a TV conveniently.

To run:

```
yarn install
node index.js -d your-media-folder
```


text:
    Module Name: Adloox Ad Server Video
    Module Type: Ad Server Video
    Maintainer: contact@adloox.com

# Description

Ad Server Video for adloox.com. Contact contact@adloox.com for information.

This module pairs with the [Adloox Analytics Adapter](./adlooxAnalyticsAdapter.md) to provide video tracking and measurement.

Prebid.js does not support [`bidWon` events for video](https://github.com/prebid/prebid.github.io/issues/1320) without the [Instream Video Ads Tracking](https://docs.prebid.org/dev-docs/modules/instreamTracking.html) module that has the limitations:

 * works only with instream video
 * viewability metrics are *not* [MRC accredited](http://mediaratingcouncil.org/)

This module has two modes of operation configurable with the `wrap` parameter below:

 * **`true` [default]:**
     * provides MRC accredited viewability measurement of your [IAB](https://www.iab.com/) [VPAID](https://iabtechlab.com/standards/video-player-ad-interface-definition-vpaid/) and [OM SDK](https://iabtechlab.com/standards/open-measurement-sdk/) enabled inventory
     * VAST tracking is collected by Adloox
     * wraps the winning bid VAST URL with the Adloox VAST/VPAID wrapper (`https://j.adlooxtracking.com/ads/vast/tag.php?...`)
 * **`false`:**
     * sends a `bidWon` event *only* to the Adloox Analytics Adapter
     * inventory is measured
     * viewability metrics are *not* MRC accredited.
     * VAST tracking is *not* collected by Adloox

**N.B.** this module is compatible for use alongside the Instream Video Ads Tracking module though not required in order to function

## Example

To view an example of an Adloox integration look at the example provided in the [Adloox Analytics Adapter documentation](./adlooxAnalyticsAdapter.md#example).

# Integration

To use this, you *must* also integrate the [Adloox Analytics Adapter](./adlooxAnalyticsAdapter.md) (and optionally the Instream Video Ads Tracking module) as shown below:

    function sendAdserverRequest(bids, timedOut, auctionId) {
      if (pbjs.initAdserverSet) return;
      pbjs.initAdserverSet = true;

      // handle display tags as usual
      googletag.cmd.push(function() {
        pbjs.setTargetingForGPTAsync && pbjs.setTargetingForGPTAsync(adUnits);
        googletag.pubads().refresh();
      });

      // handle the bids on the video adUnit
      var videoBids = bids[videoAdUnit.code];
      if (videoBids) {
        var videoUrl = pbjs.adServers.dfp.buildVideoUrl({
          adUnit: videoAdUnit,
          params: {
            iu: '/19968336/prebid_cache_video_adunit',
            cust_params: {
              section: 'blog',
              anotherKey: 'anotherValue'
            },
            output: 'vast'
          }
        });
        pbjs.adServers.adloox.buildVideoUrl({
          adUnit: videoAdUnit,
          url: videoUrl
        }, invokeVideoPlayer);
      }
    }

The helper function takes the form:

    pbjs.adServers.adloox.buildVideoUrl(options, callback)

Where:

 * **`options`:** configuration object:
     * **`adUnit`:** ad unit that is being filled
     * **`bid` [optional]:** if you override the hardcoded `pbjs.adServers.dfp.buildVideoUrl(...)` logic that picks the first bid you *must* pass in the `bid` object you select
     * **`url`:** VAST tag URL, typically the value returned by `pbjs.adServers.dfp.buildVideoUrl(...)`
     * **`wrap`:**
         * **`true` [default]:** VAST tag is be converted to an Adloox VAST wrapped tag
         * **`false`:** VAST tag URL is returned as is
     * **`blob`:**
         * **`true` [default]:** [Blob URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) is returned so that the VAST tag is only fetched once
             * only has an affect when `wrap` is set to `true`
         * **`false`:** VAST tag may be fetched twice depending on your Ad Server and video player configuration
             * use when the ad is served into a cross-origin (non-friendly) IFRAME
             * use if during QAing you discover your video player does not supports Blob URLs; widely supported (including JW Player) so contact your player vendor to resolve this where possible for the best user and device experience
 * **`callback`:** function you use to pass the VAST tag URL to your video player

**N.B.** call `pbjs.adServers.adloox.buildVideoUrl(...)` as close as possible to starting the ad to reduce impression discrepancies


text:
package azgo

import (
	"encoding/xml"
	log "github.com/sirupsen/logrus"
	"reflect"
)

// SnapmirrorPolicyGetIterRequest is a structure to represent a snapmirror-policy-get-iter Request ZAPI object
type SnapmirrorPolicyGetIterRequest struct {
	XMLName              xml.Name                                         `xml:"snapmirror-policy-get-iter"`
	DesiredAttributesPtr *SnapmirrorPolicyGetIterRequestDesiredAttributes `xml:"desired-attributes"`
	MaxRecordsPtr        *int                                             `xml:"max-records"`
	QueryPtr             *SnapmirrorPolicyGetIterRequestQuery             `xml:"query"`
	TagPtr               *string                                          `xml:"tag"`
}

// SnapmirrorPolicyGetIterResponse is a structure to represent a snapmirror-policy-get-iter Response ZAPI object
type SnapmirrorPolicyGetIterResponse struct {
	XMLName         xml.Name                              `xml:"netapp"`
	ResponseVersion string                                `xml:"version,attr"`
	ResponseXmlns   string                                `xml:"xmlns,attr"`
	Result          SnapmirrorPolicyGetIterResponseResult `xml:"results"`
}

// NewSnapmirrorPolicyGetIterResponse is a factory method for creating new instances of SnapmirrorPolicyGetIterResponse objects
func NewSnapmirrorPolicyGetIterResponse() *SnapmirrorPolicyGetIterResponse {
	return &SnapmirrorPolicyGetIterResponse{}
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterResponse) String() string {
	return ToString(reflect.ValueOf(o))
}

// ToXML converts this object into an xml string representation
func (o *SnapmirrorPolicyGetIterResponse) ToXML() (string, error) {
	output, err := xml.MarshalIndent(o, " ", "    ")
	if err != nil {
		log.Errorf("error: %v", err)
	}
	return string(output), err
}

// SnapmirrorPolicyGetIterResponseResult is a structure to represent a snapmirror-policy-get-iter Response Result ZAPI object
type SnapmirrorPolicyGetIterResponseResult struct {
	XMLName           xml.Name                                             `xml:"results"`
	ResultStatusAttr  string                                               `xml:"status,attr"`
	ResultReasonAttr  string                                               `xml:"reason,attr"`
	ResultErrnoAttr   string                                               `xml:"errno,attr"`
	AttributesListPtr *SnapmirrorPolicyGetIterResponseResultAttributesList `xml:"attributes-list"`
	NextTagPtr        *string                                              `xml:"next-tag"`
	NumRecordsPtr     *int                                                 `xml:"num-records"`
}

// NewSnapmirrorPolicyGetIterRequest is a factory method for creating new instances of SnapmirrorPolicyGetIterRequest objects
func NewSnapmirrorPolicyGetIterRequest() *SnapmirrorPolicyGetIterRequest {
	return &SnapmirrorPolicyGetIterRequest{}
}

// NewSnapmirrorPolicyGetIterResponseResult is a factory method for creating new instances of SnapmirrorPolicyGetIterResponseResult objects
func NewSnapmirrorPolicyGetIterResponseResult() *SnapmirrorPolicyGetIterResponseResult {
	return &SnapmirrorPolicyGetIterResponseResult{}
}

// ToXML converts this object into an xml string representation
func (o *SnapmirrorPolicyGetIterRequest) ToXML() (string, error) {
	output, err := xml.MarshalIndent(o, " ", "    ")
	if err != nil {
		log.Errorf("error: %v", err)
	}
	return string(output), err
}

// ToXML converts this object into an xml string representation
func (o *SnapmirrorPolicyGetIterResponseResult) ToXML() (string, error) {
	output, err := xml.MarshalIndent(o, " ", "    ")
	if err != nil {
		log.Errorf("error: %v", err)
	}
	return string(output), err
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterRequest) String() string {
	return ToString(reflect.ValueOf(o))
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterResponseResult) String() string {
	return ToString(reflect.ValueOf(o))
}

// ExecuteUsing converts this object to a ZAPI XML representation and uses the supplied ZapiRunner to send to a filer

func (o *SnapmirrorPolicyGetIterRequest) ExecuteUsing(zr *ZapiRunner) (*SnapmirrorPolicyGetIterResponse, error) {
	return o.executeWithIteration(zr)
}

// executeWithoutIteration converts this object to a ZAPI XML representation and uses the supplied ZapiRunner to send to a filer

func (o *SnapmirrorPolicyGetIterRequest) executeWithoutIteration(zr *ZapiRunner) (*SnapmirrorPolicyGetIterResponse, error) {
	result, err := zr.ExecuteUsing(o, "SnapmirrorPolicyGetIterRequest", NewSnapmirrorPolicyGetIterResponse())
	if result == nil {
		return nil, err
	}
	return result.(*SnapmirrorPolicyGetIterResponse), err
}

// executeWithIteration converts this object to a ZAPI XML representation and uses the supplied ZapiRunner to send to a filer
func (o *SnapmirrorPolicyGetIterRequest) executeWithIteration(zr *ZapiRunner) (*SnapmirrorPolicyGetIterResponse, error) {
	combined := NewSnapmirrorPolicyGetIterResponse()
	combined.Result.SetAttributesList(SnapmirrorPolicyGetIterResponseResultAttributesList{})
	var nextTagPtr *string
	done := false
	for !done {
		n, err := o.executeWithoutIteration(zr)

		if err != nil {
			return nil, err
		}
		nextTagPtr = n.Result.NextTagPtr
		if nextTagPtr == nil {
			done = true
		} else {
			o.SetTag(*nextTagPtr)
		}

		if n.Result.NumRecordsPtr == nil {
			done = true
		} else {
			recordsRead := n.Result.NumRecords()
			if recordsRead == 0 {
				done = true
			}
		}

		if n.Result.AttributesListPtr != nil {
			if combined.Result.AttributesListPtr == nil {
				combined.Result.SetAttributesList(SnapmirrorPolicyGetIterResponseResultAttributesList{})
			}
			combinedAttributesList := combined.Result.AttributesList()
			combinedAttributes := combinedAttributesList.values()

			resultAttributesList := n.Result.AttributesList()
			resultAttributes := resultAttributesList.values()

			combined.Result.AttributesListPtr.setValues(append(combinedAttributes, resultAttributes...))
		}

		if done {

			combined.Result.ResultErrnoAttr = n.Result.ResultErrnoAttr
			combined.Result.ResultReasonAttr = n.Result.ResultReasonAttr
			combined.Result.ResultStatusAttr = n.Result.ResultStatusAttr

			combinedAttributesList := combined.Result.AttributesList()
			combinedAttributes := combinedAttributesList.values()
			combined.Result.SetNumRecords(len(combinedAttributes))

		}
	}
	return combined, nil
}

// SnapmirrorPolicyGetIterRequestDesiredAttributes is a wrapper
type SnapmirrorPolicyGetIterRequestDesiredAttributes struct {
	XMLName                 xml.Name                  `xml:"desired-attributes"`
	SnapmirrorPolicyInfoPtr *SnapmirrorPolicyInfoType `xml:"snapmirror-policy-info"`
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterRequestDesiredAttributes) String() string {
	return ToString(reflect.ValueOf(o))
}

// SnapmirrorPolicyInfo is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequestDesiredAttributes) SnapmirrorPolicyInfo() SnapmirrorPolicyInfoType {
	var r SnapmirrorPolicyInfoType
	if o.SnapmirrorPolicyInfoPtr == nil {
		return r
	}
	r = *o.SnapmirrorPolicyInfoPtr
	return r
}

// SetSnapmirrorPolicyInfo is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequestDesiredAttributes) SetSnapmirrorPolicyInfo(newValue SnapmirrorPolicyInfoType) *SnapmirrorPolicyGetIterRequestDesiredAttributes {
	o.SnapmirrorPolicyInfoPtr = &newValue
	return o
}

// DesiredAttributes is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequest) DesiredAttributes() SnapmirrorPolicyGetIterRequestDesiredAttributes {
	var r SnapmirrorPolicyGetIterRequestDesiredAttributes
	if o.DesiredAttributesPtr == nil {
		return r
	}
	r = *o.DesiredAttributesPtr
	return r
}

// SetDesiredAttributes is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequest) SetDesiredAttributes(newValue SnapmirrorPolicyGetIterRequestDesiredAttributes) *SnapmirrorPolicyGetIterRequest {
	o.DesiredAttributesPtr = &newValue
	return o
}

// MaxRecords is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequest) MaxRecords() int {
	var r int
	if o.MaxRecordsPtr == nil {
		return r
	}
	r = *o.MaxRecordsPtr
	return r
}

// SetMaxRecords is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequest) SetMaxRecords(newValue int) *SnapmirrorPolicyGetIterRequest {
	o.MaxRecordsPtr = &newValue
	return o
}

// SnapmirrorPolicyGetIterRequestQuery is a wrapper
type SnapmirrorPolicyGetIterRequestQuery struct {
	XMLName                 xml.Name                  `xml:"query"`
	SnapmirrorPolicyInfoPtr *SnapmirrorPolicyInfoType `xml:"snapmirror-policy-info"`
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterRequestQuery) String() string {
	return ToString(reflect.ValueOf(o))
}

// SnapmirrorPolicyInfo is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequestQuery) SnapmirrorPolicyInfo() SnapmirrorPolicyInfoType {
	var r SnapmirrorPolicyInfoType
	if o.SnapmirrorPolicyInfoPtr == nil {
		return r
	}
	r = *o.SnapmirrorPolicyInfoPtr
	return r
}

// SetSnapmirrorPolicyInfo is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequestQuery) SetSnapmirrorPolicyInfo(newValue SnapmirrorPolicyInfoType) *SnapmirrorPolicyGetIterRequestQuery {
	o.SnapmirrorPolicyInfoPtr = &newValue
	return o
}

// Query is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequest) Query() SnapmirrorPolicyGetIterRequestQuery {
	var r SnapmirrorPolicyGetIterRequestQuery
	if o.QueryPtr == nil {
		return r
	}
	r = *o.QueryPtr
	return r
}

// SetQuery is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequest) SetQuery(newValue SnapmirrorPolicyGetIterRequestQuery) *SnapmirrorPolicyGetIterRequest {
	o.QueryPtr = &newValue
	return o
}

// Tag is a 'getter' method
func (o *SnapmirrorPolicyGetIterRequest) Tag() string {
	var r string
	if o.TagPtr == nil {
		return r
	}
	r = *o.TagPtr
	return r
}

// SetTag is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterRequest) SetTag(newValue string) *SnapmirrorPolicyGetIterRequest {
	o.TagPtr = &newValue
	return o
}

// SnapmirrorPolicyGetIterResponseResultAttributesList is a wrapper
type SnapmirrorPolicyGetIterResponseResultAttributesList struct {
	XMLName                 xml.Name                   `xml:"attributes-list"`
	SnapmirrorPolicyInfoPtr []SnapmirrorPolicyInfoType `xml:"snapmirror-policy-info"`
}

// String returns a string representation of this object's fields and implements the Stringer interface
func (o SnapmirrorPolicyGetIterResponseResultAttributesList) String() string {
	return ToString(reflect.ValueOf(o))
}

// SnapmirrorPolicyInfo is a 'getter' method
func (o *SnapmirrorPolicyGetIterResponseResultAttributesList) SnapmirrorPolicyInfo() []SnapmirrorPolicyInfoType {
	r := o.SnapmirrorPolicyInfoPtr
	return r
}

// SetSnapmirrorPolicyInfo is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterResponseResultAttributesList) SetSnapmirrorPolicyInfo(newValue []SnapmirrorPolicyInfoType) *SnapmirrorPolicyGetIterResponseResultAttributesList {
	newSlice := make([]SnapmirrorPolicyInfoType, len(newValue))
	copy(newSlice, newValue)
	o.SnapmirrorPolicyInfoPtr = newSlice
	return o
}

// values is a 'getter' method
func (o *SnapmirrorPolicyGetIterResponseResultAttributesList) values() []SnapmirrorPolicyInfoType {
	r := o.SnapmirrorPolicyInfoPtr
	return r
}

// setValues is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterResponseResultAttributesList) setValues(newValue []SnapmirrorPolicyInfoType) *SnapmirrorPolicyGetIterResponseResultAttributesList {
	newSlice := make([]SnapmirrorPolicyInfoType, len(newValue))
	copy(newSlice, newValue)
	o.SnapmirrorPolicyInfoPtr = newSlice
	return o
}

// AttributesList is a 'getter' method
func (o *SnapmirrorPolicyGetIterResponseResult) AttributesList() SnapmirrorPolicyGetIterResponseResultAttributesList {
	var r SnapmirrorPolicyGetIterResponseResultAttributesList
	if o.AttributesListPtr == nil {
		return r
	}
	r = *o.AttributesListPtr
	return r
}

// SetAttributesList is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterResponseResult) SetAttributesList(newValue SnapmirrorPolicyGetIterResponseResultAttributesList) *SnapmirrorPolicyGetIterResponseResult {
	o.AttributesListPtr = &newValue
	return o
}

// NextTag is a 'getter' method
func (o *SnapmirrorPolicyGetIterResponseResult) NextTag() string {
	var r string
	if o.NextTagPtr == nil {
		return r
	}
	r = *o.NextTagPtr
	return r
}

// SetNextTag is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterResponseResult) SetNextTag(newValue string) *SnapmirrorPolicyGetIterResponseResult {
	o.NextTagPtr = &newValue
	return o
}

// NumRecords is a 'getter' method
func (o *SnapmirrorPolicyGetIterResponseResult) NumRecords() int {
	var r int
	if o.NumRecordsPtr == nil {
		return r
	}
	r = *o.NumRecordsPtr
	return r
}

// SetNumRecords is a fluent style 'setter' method that can be chained
func (o *SnapmirrorPolicyGetIterResponseResult) SetNumRecords(newValue int) *SnapmirrorPolicyGetIterResponseResult {
	o.NumRecordsPtr = &newValue
	return o
}


text:
<?php
namespace XeroPHP\Models\PayrollAU\Employee;

use XeroPHP\Remote;

class HomeAddress extends Remote\Object
{

    /**
     * Address line 1 for employee home address (max length = 50)
     *
     * @property string AddressLine1
     */

    /**
     * Address line 2 for employee home address (max length = 50)
     *
     * @property string AddressLine2
     */

    /**
     * Suburb for employee home address (max length = 50)
     *
     * @property string City
     */

    /**
     * State abbreviation for employee home address
     *
     * @property string Region
     */

    /**
     * PostCode for employee home address (max length = 4)
     *
     * @property string PostalCode
     */

    /**
     * Country of HomeAddress
     *
     * @property string Country
     */

    /**
     * Get the resource uri of the class (Contacts) etc
     *
     * @return string
     */
    public static function getResourceURI()
    {
        return 'HomeAddress';
    }

    /**
     * Get the root node name.  Just the unqualified classname
     *
     * @return string
     */
    public static function getRootNodeName()
    {
        return 'HomeAddress';
    }

    /**
     * Get the guid property
     *
     * @return string
     */
    public static function getGUIDProperty()
    {
        return '';
    }

    /**
     * Get the stem of the API (core.xro) etc
     *
     * @return string|null
     */
    public static function getAPIStem()
    {
        return Remote\URL::API_PAYROLL;
    }

    /**
     * Get the supported methods
     */
    public static function getSupportedMethods()
    {
        return [
        ];
    }

    /**
     *
     * Get the properties of the object.  Indexed by constants
     *  [0] - Mandatory
     *  [1] - Type
     *  [2] - PHP type
     *  [3] - Is an Array
     *  [4] - Saves directly
     *
     * @return array
     */
    public static function getProperties()
    {
        return [
            'AddressLine1' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'AddressLine2' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'City' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Region' => [false, self::PROPERTY_TYPE_ENUM, null, false, false],
            'PostalCode' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Country' => [false, self::PROPERTY_TYPE_STRING, null, false, false]
        ];
    }

    public static function isPageable()
    {
        return false;
    }

    /**
     * @return string
     */
    public function getAddressLine1()
    {
        return $this->_data['AddressLine1'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setAddressLine1($value)
    {
        $this->propertyUpdated('AddressLine1', $value);
        $this->_data['AddressLine1'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getAddressLine2()
    {
        return $this->_data['AddressLine2'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setAddressLine2($value)
    {
        $this->propertyUpdated('AddressLine2', $value);
        $this->_data['AddressLine2'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getCity()
    {
        return $this->_data['City'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setCity($value)
    {
        $this->propertyUpdated('City', $value);
        $this->_data['City'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->_data['Region'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setRegion($value)
    {
        $this->propertyUpdated('Region', $value);
        $this->_data['Region'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getPostalCode()
    {
        return $this->_data['PostalCode'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setPostalCode($value)
    {
        $this->propertyUpdated('PostalCode', $value);
        $this->_data['PostalCode'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getCountry()
    {
        return $this->_data['Country'];
    }

    /**
     * @param string $value
     * @return HomeAddress
     */
    public function setCountry($value)
    {
        $this->propertyUpdated('Country', $value);
        $this->_data['Country'] = $value;
        return $this;
    }

}


text:
const http = require('http');

const TIMEOUT = 5000;

/**
 * Makes an HTTP GET request using either a url string or an options object.
 * Success or failure is handled by callbacks.
 * @module GET/cbRequest
 * @param {string} url - Request either this or options object
 * @param {object} options - Request either this or url string
 * @param {function} cb - Call on request end or error
 * @return {void}
 * @example
 * cbRequest('http://google.com', (err, res) => {});
 */
module.exports = function cbRequest({url, options, cb}) {
  try {
    http.get(url || options, (res) => {
      res.body = '';
      res.on('data', (c) => res.body += c).on('end', () => cb(null, res));
    }).on('error', (err) => cb(err))
      .setTimeout(TIMEOUT, function () { this.abort(); });
  }
  catch (err) { cb(err); }
};


text:
<?php
namespace Ineersa\Converter\Cache;

use Ineersa\Converter\Interfaces\CacheInterface;

class MemcacheCache implements CacheInterface
{

    /**
     * Cache expiration time, 2 hours default
     * @var int
     */
    public $expire = 7200;

    public $host = 'localhost';

    public $port = 11211;

    /**
     * @var \Memcached
     */
    private $memcache;

    public function __construct()
    {
        $this->setupMemcache();
    }

    private function setupMemcache()
    {
        if (is_null($this->memcache) && class_exists('Memcached', false)){
            $this->memcache = new \Memcached();
            $this->memcache->addServer($this->host, $this->port);
        }
    }

    /**
     * @param $key
     * @param $data
     * @return bool
     */
    public function set($key, $data)
    {
        if(!is_null($this->memcache))
            $this->memcache->set($key, $data, $this->expire);
        return false;
    }

    /**
     * @param $key
     * @return mixed
     */
    public function get($key)
    {
        if(!is_null($this->memcache))
            return $this->memcache->get($key);
        return false;
    }
}


text:
title: Area Calculator
localeTitle: Калькулятор площади
---
## Калькулятор площади

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/tools/calculators/area-calculator/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Дополнительная информация:


text:
<?xml version="1.0" encoding="utf-8"?>
<GameData>
  <LocalizedText>
    <!-- GERMAN -->

    <!-- IDS -->
    <Replace Tag="LOC_IDS_DUMMY_KEY" Language="de_DE">
      <Text>Handelsübersicht</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_TERMS" Language="de_DE">
      <Text>Handelsbedingungen</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_CEDE" Language="de_DE">
      <Text>Zurücktreten</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_RETURN" Language="de_DE">
      <Text>Zurück</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_TRADE" Language="de_DE">
      <Text>[COLOR_Red]Handel[ENDCOLOR] mit</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_SUZERAIN" Language="de_DE">
      <Text>[COLOR_Civ6Blue]Suzerän[ENDCOLOR] von</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_UNTRADEABLE" Language="de_DE">
      <Text>nicht handelbar</Text>
    </Replace>
    <Replace Tag="LOC_IDS_DEAL_DUPLICATE" Language="de_DE"
      <Text>Wiederholen</Text>
    </Replace>

  </LocalizedText>
</GameData>