text:
package gr.di.uoa.a8.bvplus.utils;

import it.unimi.dsi.webgraph.ArcListASCIIGraph;
import it.unimi.dsi.webgraph.BVGraph;
import it.unimi.dsi.webgraph.ImmutableGraph;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class PerformComparison {

	private static Set<Integer> nodes = new HashSet<Integer>();
	private static int size;
	private static int edges = 0;
	private static HashMap<Integer,Long> sizes = new HashMap<Integer, Long>();

	private static void createNoDFile(String filename, int D) throws IOException
	{
		BufferedReader br = new BufferedReader(new FileReader(filename));
		File file = new File(filename+".noD"+D);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);
		String line;
		int max = -1;
		while ((line = br.readLine()) != null) {
			String[] temp = line.split("\\s+");
			int a = Integer.parseInt(temp[0]);
			int b = Integer.parseInt(temp[1]);
			// only for one iteration
			if(D==1)
			{
				edges++;
				nodes.add(a);
				nodes.add(b);
				if(a+1>max)
					max = a+1;
				if(b+1>max)
					max = b+1;
				size = max;
			}
			if(a>=b-D && a<=b+D)
			{

			}
			else
			{
				bw.write(line+'\n');
			}
		}
		br.close();
		bw.close();
	}

	public static void main(String[] args) throws FileNotFoundException, IOException {

		String filename = args[0];
		int iterations = Integer.parseInt(args[1]);
		boolean social = Boolean.parseBoolean(args[2]);
		boolean undirected = Boolean.parseBoolean(args[2]);

		System.out.println(filename);

		for(int i=1;i<=iterations;i++)
		{
			createNoDFile(filename, i);
		}

		for(int i=0;i<=iterations;i++)
		{
			String temp = filename + (i!=0 ? ".noD"+i : "");
			ImmutableGraph ig  = ArcListASCIIGraph.loadOnce(new FileInputStream(new File(temp)));
			ImmutableGraph.store(BVGraph.class, ig, temp+".boldi");
			sizes.put(i, new File(temp+".boldi.graph").length()+new File(temp+".boldi.offsets").length()+new File(temp+".boldi.properties").length());
		}

		System.out.println("Boldi: "+(sizes.get(0)*8/(float)edges));
		for(int i=1;i<=iterations;i++)
		{
			System.out.println(i+": "+((sizes.get(i)*8 + size*((undirected ? 1 : 2)*i+(social ? 0 : 1)))/(float)edges)+" ("+((sizes.get(i)*8)/(float)edges)+")");
			System.out.println((size*((undirected ? 1 : 2)*i+(social ? 0 : 1))));
		}
	}

}


text:
{% extends "admin/edit.html" %}

{% block form_action %}/api/announcements/{{ announcement.key() }}/edit/{% endblock %}

{% block form_fields %}

    title
    <input type="text" name="title" value="{{ announcement.title }}" />

    faculty
    <input type="text" name="faculty" value="{{ announcement.faculty }}" />

    venue
    <input type="text" name="venue" value="{{ announcement.venue }}" />

  <fieldset><legend>brochure</legend>

      brochure url
      <input type="text" name="brochure_url" value="{{ announcement.brochure_url }}" />

      Upload image here and then paste the link in this text box.

        description
        <textarea name="description" rows="20" cols="70">{{ announcement.description }}</textarea>

  </fieldset>

  <fieldset><legend>dates</legend>

      from date/time
      <input type="text" name="when_from" value="{{ announcement.when_from|datetimeformat('%Y-%m-%dT%H:%M:%S') }}" id="edit-when-from" />
      The date and time of the commencement of the program.

      to date/time
      <input type="text" name="when_to" value="{{ announcement.when_to|datetimeformat('%Y-%m-%dT%H:%M:%S') }}" id="edit-when-to" />
      The date and time of the end of the program.

      payment calculation date
      <input type="text" name="when_payment_is_calculated" id="edit-when-payment-is-calculated" value="{{ announcement.when_payment_is_calculated|datetimeformat('%Y-%m-%dT%H:%M:%S') }}" class="required" />
      Payment calculations will occur on this date and emails will be dispatched to registered nominees.

      registration closure date
      <input type="text" name="when_registration_ends" value="{{ announcement.when_registration_ends|datetimeformat('%Y-%m-%dT%H:%M:%S') }}" id="edit-when-registration-ends" />
      Registrations received after this date will receive "Thank you for your interest." message.

  </fieldset>

  <fieldset>
    <legend>participation</legend>

      maximum participants
      <input type="text" name="max_participants" value="{{ announcement.max_participants }}" />

    {% for fee in announcement.fees %}

      fees
      <input type="text" name="fees_{{ loop.index }}" value="{{ fee.fee }}" />
      for participants
      <input type="text" name="participants_{{ loop.index }}" value="{{ fee.for_participant_count }}" />

    {% endfor %}
  </fieldset>

{% endblock %}

{% block tag_form_additional_content %}

Registrants (total: {{ announcement.total_participant_count }}, active: {{ announcement.participant_count }})

  {% for registrant in registrants %}

{{ registrant.full_name }} {% if registrant.is_payment_received %}(paid){% endif %} {{ registrant.designation }}, {{ registrant.company }} {{ registrant.email }}, {{ registrant.phone_number }} - {{ registrant.when_created|datetimeformat('%A, %B %d, %Y - %H:%M:%S') }} UTC

✔ Approve Attendance

✔ Unapprove Attendance

✔ Confirm Payment (sends email)

      #*
× Reverse Payment (sends email)
*#

    {% if registrant.why_unregister %}
Why unregistered?

{{ registrant.why_unregister }}
{% endif %}

  {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
package com.andexert.calendarlistview.library;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ListView;

public class DayPickerView extends RecyclerView
{
    protected Context mContext;
	protected SimpleMonthAdapter mAdapter;
	private DatePickerController mController;
    protected int mCurrentScrollState = 0;
	private boolean mPerformingScroll;
	protected long mPreviousScrollPosition;
	protected int mPreviousScrollState = 0;
    final TypedArray typedArray;
    private final AttributeSet attrs;
    private OnScrollListener onScrollListener;

    public DayPickerView(Context context)
    {
        this(context, null);
    }

    public DayPickerView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public DayPickerView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        this.attrs = attrs;
        typedArray = context.obtainStyledAttributes(attrs, R.styleable.DayPickerView);
        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        init(context);
    }

    public void setmController(DatePickerController mController)
    {
        this.mController = mController;
        setUpAdapter();
        setAdapter(mAdapter);
    }

	public void init(Context paramContext) {
        setLayoutManager(new LinearLayoutManager(paramContext));
		mContext = paramContext;
		setUpListView();

        onScrollListener = new OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                super.onScrolled(recyclerView, dx, dy);
                SimpleMonthView child = (SimpleMonthView) recyclerView.getChildAt(0);
                if (child == null) {
                    return;
                }

                mPreviousScrollPosition = dy;
                mPreviousScrollState = mCurrentScrollState;
            }
        };
	}

	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

	}

	protected void setUpAdapter() {
		if (mAdapter == null) {
			mAdapter = new SimpleMonthAdapter(getContext(), mController, typedArray);
        }
		mAdapter.notifyDataSetChanged();
	}

	protected void setUpListView() {
		setVerticalScrollBarEnabled(false);
		setOnScrollListener(onScrollListener);
		setFadingEdgeLength(0);
	}

    public SimpleMonthAdapter.SelectedDays<SimpleMonthAdapter.CalendarDay> getSelectedDays()
    {
        return mAdapter.getSelectedDays();
    }
}


text:
import React, {Component} from 'react';
import Sidebar from './Sidebar';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
import Rightbar from './Rightbar';
import $ from 'jquery';

export default class Content extends Component {

  componentDidMount() {
    $(document.body).addClass('hold-transition skin-blue sidebar-mini');
    // class="hold-transition skin-blue sidebar-mini"
  }

  componentWillUnmount() {
    $(document.body).removeClass('hold-transition skin-blue sidebar-mini');
  }

  render() {
    return (

        <PageHeader />
        <Sidebar />

              Page Header
              Optional description *

 Level

Here

            {this.props.children}

        <PageFooter />
        <Rightbar />

    );
  }
}


text:
package io.gravitee.am.repository.jdbc.management.api.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author Eric LELEU (eric.leleu at graviteesource.com)
 * @author GraviteeSource Team
 */
@Table("applications")
public class JdbcApplication {
    @Id
    private String id;
    private String name;
    private String type;
    private String description;
    private String domain;

    private boolean enabled;
    private boolean template;
    private String certificate;
    @Column("created_at")
    private LocalDateTime createdAt;
    @Column("updated_at")
    private LocalDateTime updatedAt;
    // JSON
    private String metadata;
    private String settings;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isTemplate() {
        return template;
    }

    public void setTemplate(boolean template) {
        this.template = template;
    }

    public String getCertificate() {
        return certificate;
    }

    public void setCertificate(String certificate) {
        this.certificate = certificate;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getMetadata() {
        return metadata;
    }

    public void setMetadata(String metadata) {
        this.metadata = metadata;
    }

    public String getSettings() {
        return settings;
    }

    public void setSettings(String settings) {
        this.settings = settings;
    }

    @Table("application_identities")
    public static class Identity {
        @Column("application_id")
        private String applicationId;
        private String identity;

        public String getApplicationId() {
            return applicationId;
        }

        public void setApplicationId(String applicationId) {
            this.applicationId = applicationId;
        }

        public String getIdentity() {
            return identity;
        }

        public void setIdentity(String identity) {
            this.identity = identity;
        }
    }

    @Table("application_grants")
    public static class Grant {
        @Column("application_id")
        private String applicationId;
        @Column("grant_type")
        private String grant;

        public String getApplicationId() {
            return applicationId;
        }

        public void setApplicationId(String applicationId) {
            this.applicationId = applicationId;
        }

        public String getGrant() {
            return grant;
        }

        public void setGrant(String grant) {
            this.grant = grant;
        }
    }

    @Table("application_factors")
    public static class Factor {
        @Column("application_id")
        private String applicationId;
        private String factor;

        public String getApplicationId() {
            return applicationId;
        }

        public void setApplicationId(String applicationId) {
            this.applicationId = applicationId;
        }

        public String getFactor() {
            return factor;
        }

        public void setFactor(String factor) {
            this.factor = factor;
        }
    }
}


text:
package com.github.s7connector.test.example;

import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.api.S7Type;

/**
 * @author Thomas Rudin (thomas@rudin-informatik.ch)
 *
 */
public class MyDataBean
{
	@S7Variable(byteOffset=0, bitOffset=0, type=S7Type.BOOL)
	public boolean bit1;

	@S7Variable(byteOffset=0, bitOffset=1, type=S7Type.BOOL)
	public boolean bit2;

	@S7Variable(byteOffset=1, type=S7Type.BYTE)
	public byte someByte;

	@S7Variable(byteOffset=2, type=S7Type.WORD)
	public int myNumber;

}


text:
package com.giffing.easyxml.jdom2.writer;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;

import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.output.Format;
import org.jdom2.output.support.StAXStreamProcessor;
import org.jdom2.transform.JDOMResult;

import com.giffing.easyxml.context.ParseContext;
import com.giffing.easyxml.jdom2.writer.context.Jdom2WriterContext;
import com.giffing.easyxml.jdom2.writer.processor.CustomStAXStreamProcessor;
import com.giffing.easyxml.reader.item.ItemReader;
import com.giffing.easyxml.stax.reader.context.StaxTransformerResult;
import com.giffing.easyxml.util.ReaderToWriter;

public class Writer {

	private InputStream inputStream;

	private OutputStream outputStream;

	private ParseContext parseContext = new ParseContext();

	private String namespace;

	private String encoding = "UTF-8";

	private Format format = Format.getPrettyFormat();

	private List<Jdom2ItemWriter> itemWriter = new ArrayList<>();

	private List<ItemReader<XMLStreamReader, Void>> staxItemReaders = new ArrayList<>();

	public void writeAll()
		throws XMLStreamException,
		Exception {

		// Assert.notNull(documentFileResult);
		// Assert.notNull(outputFile);
		// Assert.notNull(packetDirection);

		XMLInputFactory xif = XMLInputFactory.newInstance();
		XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
		TransformerFactory tf = TransformerFactory.newInstance();
		StAXStreamProcessor processor = new CustomStAXStreamProcessor(namespace);
		XMLStreamReader xsr = null;
		XMLStreamWriter writer = null;

		xsr = xif.createXMLStreamReader(inputStream, encoding);
		writer = outputFactory.createXMLStreamWriter(outputStream, encoding);

		ReaderToWriter readToWrite = new ReaderToWriter();
		readToWrite.setStreamWriter(writer);

		xsr.nextTag();

		Transformer t = tf.newTransformer();
		List<String> currentElementPath = new ArrayList<>();

		while (xsr.hasNext()) {
			if (xsr.isEndElement()) {
				if (currentElementPath.size() > 0)
					currentElementPath.remove(currentElementPath.size() - 1);
			}
			if (xsr.isStartElement()) {
				String localName = xsr.getLocalName();
				currentElementPath.add(localName);
				boolean handled = false;
				String joinPath = StringUtils.join(currentElementPath, "/");
				parseContext.setPath(joinPath);

				for (ItemReader<XMLStreamReader, Void> staxItemReader : staxItemReaders) {
					if(staxItemReader.shouldHandle(parseContext)) {
						staxItemReader.read(new StaxTransformerResult(xsr).getContent());
					}
				}

				for (Jdom2ItemWriter itemWriter : this.itemWriter) {
					if (itemWriter.shouldHandle(parseContext)) {
						JDOMResult result = new JDOMResult();
						t.transform(new StAXSource(xsr), result);
						Document document = result.getDocument();
						Element rootElement = document.getRootElement();
						rootElement.addNamespaceDeclaration(Namespace.getNamespace(namespace));
						Jdom2WriterContext context = new Jdom2WriterContext(parseContext, rootElement);
						if(!itemWriter.shouldRemove(context)) {
							itemWriter.handle(context);
							processor.process(writer, format, rootElement);
						}
						handled = true;
						break;
					}
				}
				if (handled) {
					if (currentElementPath.size() > 0)
						currentElementPath.remove(currentElementPath.size() - 1);
				} else {
					readToWrite.write(xsr);
				}
			} else {
				readToWrite.write(xsr);
			}
			if (xsr.hasNext()) {
				try {
					xsr.next();
				} catch (Exception e) {
					throw e;
				}
			}
		}
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	public void setOutputStream(OutputStream outputStream) {
		this.outputStream = outputStream;
	}

	public List<Jdom2ItemWriter> getItemWriter() {
		return itemWriter;
	}

	public void setItemWriter(List<Jdom2ItemWriter> itemWriter) {
		this.itemWriter = itemWriter;
	}

	public String getNamespace() {
		return namespace;
	}

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	public List<ItemReader<XMLStreamReader, Void>> getStaxItemReaders() {
		return staxItemReaders;
	}

	public void setStaxItemReaders(List<ItemReader<XMLStreamReader, Void>> staxItemReaders) {
		this.staxItemReaders = staxItemReaders;
	}

	public void setParseContext(ParseContext parseContext) {
		this.parseContext = parseContext;
	}

	public Format getFormat() {
		return format;
	}

	public void setFormat(Format format) {
		this.format = format;
	}

}


text:
// +build !nopkcs11

package factory

import (
	"github.com/hyperledger/fabric/bccsp"
	"github.com/hyperledger/fabric/bccsp/pkcs11"
	"github.com/pkg/errors"
)

// FactoryOpts holds configuration information used to initialize factory implementations
type FactoryOpts struct {
	ProviderName string             `mapstructure:"default" json:"default" yaml:"Default"`
	SwOpts       *SwOpts            `mapstructure:"SW,omitempty" json:"SW,omitempty" yaml:"SwOpts"`
	PluginOpts   *PluginOpts        `mapstructure:"PLUGIN,omitempty" json:"PLUGIN,omitempty" yaml:"PluginOpts"`
	Pkcs11Opts   *pkcs11.PKCS11Opts `mapstructure:"PKCS11,omitempty" json:"PKCS11,omitempty" yaml:"PKCS11"`
}

// InitFactories must be called before using factory interfaces
// It is acceptable to call with config = nil, in which case
// some defaults will get used
// Error is returned only if defaultBCCSP cannot be found
func InitFactories(config *FactoryOpts) error {
	factoriesInitOnce.Do(func() {
		setFactories(config)
	})

	return factoriesInitError
}

func setFactories(config *FactoryOpts) error {
	// Take some precautions on default opts
	if config == nil {
		config = GetDefaultOpts()
	}

	if config.ProviderName == "" {
		config.ProviderName = "SW"
	}

	if config.SwOpts == nil {
		config.SwOpts = GetDefaultOpts().SwOpts
	}

	// Initialize factories map
	bccspMap = make(map[string]bccsp.BCCSP)

	// Software-Based BCCSP
	if config.SwOpts != nil {
		f := &SWFactory{}
		err := initBCCSP(f, config)
		if err != nil {
			factoriesInitError = errors.Wrap(err, "Failed initializing SW.BCCSP")
		}
	}

	// PKCS11-Based BCCSP
	if config.Pkcs11Opts != nil {
		f := &PKCS11Factory{}
		err := initBCCSP(f, config)
		if err != nil {
			factoriesInitError = errors.Wrapf(err, "Failed initializing PKCS11.BCCSP %s", factoriesInitError)
		}
	}

	// BCCSP Plugin
	if config.PluginOpts != nil {
		f := &PluginFactory{}
		err := initBCCSP(f, config)
		if err != nil {
			factoriesInitError = errors.Wrapf(err, "Failed initializing PKCS11.BCCSP %s", factoriesInitError)
		}
	}

	var ok bool
	defaultBCCSP, ok = bccspMap[config.ProviderName]
	if !ok {
		factoriesInitError = errors.Errorf("%s\nCould not find default `%s` BCCSP", factoriesInitError, config.ProviderName)
	}

	return factoriesInitError
}

// GetBCCSPFromOpts returns a BCCSP created according to the options passed in input.
func GetBCCSPFromOpts(config *FactoryOpts) (bccsp.BCCSP, error) {
	var f BCCSPFactory
	switch config.ProviderName {
	case "SW":
		f = &SWFactory{}
	case "PKCS11":
		f = &PKCS11Factory{}
	case "PLUGIN":
		f = &PluginFactory{}
	default:
		return nil, errors.Errorf("Could not find BCCSP, no '%s' provider", config.ProviderName)
	}

	csp, err := f.Get(config)
	if err != nil {
		return nil, errors.Wrapf(err, "Could not initialize BCCSP %s", f.Name())
	}
	return csp, nil
}


text:
package ucar.nc2.iosp.grib;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.unidata.util.test.TestDir;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.invoke.MethodHandles;

/**
 * Keep opening files until we get an error
 *
 * @author caron
 * @since 11/4/2014
 */
public class TestFileOpenAndClose {
  private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  // @Test
  public void testNFilesOpen() throws IOException {
    File topDir = new File(TestDir.cdmUnitTestDir + "gribCollections/rdavm/ds083.2");
    openAll(topDir);
  }

  // @Test
  public void testNFilesOpenAndClose() throws IOException {
    File topDir = new File(TestDir.cdmUnitTestDir + "gribCollections/rdavm/ds083.2");
    openAndClose(topDir);
  }

  int count = 0;

  void openAll(File dir) throws IOException {
    File[] files = dir.listFiles();
    if (files == null)
      return;
    System.out.printf("%n%s%n", dir.getPath());
    for (File f : files) {
      if (f.isDirectory())
        openAll(f);
      else
        try {
          RandomAccessFile raf = new RandomAccessFile(f.getPath(), "r");
          count++;

        } catch (IOException ioe) {
          System.out.printf("%s count = %d%n", ioe.getMessage(), count);
          throw ioe;
        }
    }
  }

  void openAndClose(File dir) throws IOException {
    File[] files = dir.listFiles();
    if (files == null)
      return;
    System.out.printf("%n%s%n", dir.getPath());

    for (File f : files) {
      if (f.isDirectory()) {
        openAndClose(f);
      } else {

        try (RandomAccessFile raf = new RandomAccessFile(f.getPath(), "r")) {
          count++;
          System.out.printf("%d ", count);
          /*
           * if (count % 10000 == 0) {
           * Thread.currentThread();
           * Thread.sleep(3000);
           * System.out.printf("sleep%n");
           * }
           */

        } catch (IOException ioe) {
          System.out.printf("%n%s count = %d%n", ioe.getMessage(), count);
          throw ioe;

        } /*
           * catch (InterruptedException e) {
           * e.printStackTrace();
           * }
           */

      }

    }
  }

}


text:
package org.xmlactions.test;

public class CodeCall {

	public String toString() {
		return "toString:" + this.getClass().getName();
	}

	public String call(Object arg1, Object arg2) {
		return ("arg1(Object):" + arg1 + " arg2(Object):" + arg2);
	}

	public String call(String arg1, String arg2) {
		return ("arg1(String):" + arg1 + " arg2(String):" + arg2);
	}

	public String call(int number) {
		return "The number is(int):" + number;
	}
}


text:
package org.jkiss.dbeaver.ext.postgresql.tools;

import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.ui.tools.IUserInterfaceTool;
import org.jkiss.dbeaver.ui.dialogs.tools.ToolWizardDialog;

import java.util.Collection;

/**
 * Database export
 */
public class PostgreToolBackup implements IUserInterfaceTool
{
    @Override
    public void execute(IWorkbenchWindow window, IWorkbenchPart activePart, Collection<DBSObject> objects) throws DBException
    {
        ToolWizardDialog dialog = new ToolWizardDialog(
            window,
            new PostgreBackupWizard(objects));
        dialog.open();
    }
}


text:
<?php

require 'app/config/config.php';
require 'app/includes/helper.php';
include 'app/includes/header.php';

if( $_SERVER['REQUEST_METHOD']==='POST' ){
	// header('Location: index.php');
	$nickname = $_POST['nickname'];
	$password = $_POST['password'];
	$repassword = $_POST['repassword'];
	$name = $_POST['name'];
	$lastname = $_POST['lastname'];
	$email = $_POST['email'];

	$conn = getConnection();

	if($repassword !== $password){
		$_SESSION['message'] = "Contraseña no corresponde a la confirmación";
	}else{
		$pwd = pwdcrypt($password);
		$stm = $conn->prepare("INSERT INTO users (name, lastname, email, nickname, password) VALUES (?,?,?,?,?)");
		$stm->bind_param("sssss", $name, $lastname, $email, $nickname, $pwd);
		$inserted = $stm->execute();
		if($inserted){
			$stm->close();
			$conn->close();
			$_SESSION['message'] = 'Usuario creado correctamente. Inicie sesión';
			header('Location: login.php');
		}else{
			$_SESSION['message'] = 'No se guardo: ' . $conn->error .' '. $stm->error;
		}

	}
}

?>

<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Registrarse</title>
	<link rel="stylesheet" href="styles/login.css">

Ingrese sus datos para registrarse

		<?php if(isset($_SESSION['message'])){ ?>

<?php echo $_SESSION['message']; ?>

				<?php unset($_SESSION['message']); ?>
		<?php	} ?>
		<form action="register.php" method="post">

				<input type="text" name="name" placeholder="Nombre" required>

				<input type="text" name="lastname" placeholder="Apellido" required>

				<input type="email" name="email" placeholder="Correo electronico" required>

				<input type="text" name="nickname" placeholder="Nombre de usuario" required>

				<input type="password" name="password" placeholder="Contraseña" required>

				<input type="password" name="repassword" placeholder="Repita la contraseña" required>

<input type="submit" value="Registrarme">

«Regresar

		</form>


text:
Name: [Valid Phone Number](https://www.codewars.com/kata/valid-phone-number)

Difficulty: **6 Kyu**

# Description
Write a function that accepts a string, and returns true if it is in the form of a phone number.

# Assumptions
Assume that any integer from `0-9` in any of the spots will produce a valid phone number.

Only worry about the following format: `(123) 456-7890`

# Examples
```ruby
validPhoneNumber("(123) 456-7890")  #  returns true
validPhoneNumber("(1111)555 2345")  # returns false
validPhoneNumber("(098) 123 4567")  # returns false
```

# Scenario
```ruby
def validPhoneNumber(phoneNumber)
  #TODO
end
```


text:
import time, sys, signal, atexit
import pyupm_hyld9767 as sensorObj

# Instantiate a HYLD9767 on analog pin A0, with an analog
# reference voltage of 5.0
sensor = sensorObj.HYLD9767(0, 5.0)

## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
	raise SystemExit

# This function lets you run code on exit
def exitHandler():
	print "Exiting"
	sys.exit(0)

# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)

# Every tenth of a second, sample the loudness and output it's
# corresponding analog voltage.

while (1):
        print "Detected loudness (volts): ", sensor.loudness()
	time.sleep(.1)


text:
# uncurry

> Transform a curried function into a function invoked with multiple arguments.

## Usage

```javascript
var uncurry = require( '@stdlib/utils/uncurry' );
```

#### uncurry( fcn\[, arity]\[, thisArg] )

Transforms a curried function into a function invoked with multiple arguments.

```javascript
function add( x ) {
    return function add( y ) {
        return x + y;
    };
}

var fcn = uncurry( add );

var sum = fcn( 2, 3 );
// returns 5
```

To enforce a fixed number of parameters, provide an `arity` argument.

```javascript
function add( x ) {
    return function add( y ) {
        return x + y;
    };
}

var fcn = uncurry( add, 2 );

var sum = fcn( 9 );
// throws <Error>
```

To specify an execution context, provide a `thisArg` argument.

```javascript
function addX( x ) {
    this.x = x;
    return addY;
}

function addY( y ) {
    return this.x + y;
}

var fcn = uncurry( addX, {} );

var sum = fcn( 2, 3 );
// returns 5
```

The function supports providing both an `arity` and execution context.

```javascript
function addX( x ) {
    this.x = x;
    return addY;
}

function addY( y ) {
    return this.x + y;
}

var fcn = uncurry( addX, 2, {} );

var sum = fcn( 2, 3 );
// returns 5

sum = fcn( 4 );
// throws <Error>
```

## Examples

```javascript
var curry = require( '@stdlib/utils/curry' );
var uncurry = require( '@stdlib/utils/uncurry' );

var uncurried;
var curried;
var bool;
var out;
var i;

function add( x, y, z, w, t, s ) {
    return x + y + z + w + t + s;
}

out = add( 0, 10, 20, 30, 40, 50 );
// returns 150

// Transform `add` into a curried function:
curried = curry( add );
out = curried;
for ( i = 0; i < add.length; i++ ) {
    out = out( i*10 );
}
bool = ( out === 150 );
// returns true

// Uncurry a curried function:
uncurried = uncurry( curried );

out = uncurried( 0, 10, 20, 30, 40, 50 );
// returns 150
```

* * *

## See Also

-   [`@stdlib/utils/curry`][@stdlib/utils/curry]: transform a function into a sequence of functions each accepting a single argument.
-   [`@stdlib/utils/uncurry-right`][@stdlib/utils/uncurry-right]: transform a curried function into a function invoked with multiple arguments.

[@stdlib/utils/curry]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/curry

[@stdlib/utils/uncurry-right]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/uncurry-right


text:
var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    usernames = [];

app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 3000);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');

server.listen(app.get('port'), app.get('ip'), function() {
    console.log('Express Server listening on port ' + app.get('port'));
});

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.sockets.on('connection', function(socket) {
    function updateUserNames() {
        io.sockets.emit('usernames', usernames);
    }

    socket.on('new user', function(data, callback) {
        if(usernames.indexOf(data) != -1) {
            callback({
                isValid: false,
                message: 'This username is already taken!'
            });
        } else if(data !== '') {
            callback({
                isValid: true,
                message: 'Succesfully logged in!'
            });
            socket.username = data;
            usernames.push(socket.username);
            updateUserNames();
        } else {
            callback({
                isValid: false,
                message: 'This username is invalid!'
            });
        }
    });

    socket.on('send message', function(data) {
        io.sockets.emit('new message', {
            msg: data,
            user: socket.username
        });
    });

    socket.on('disconnect', function(data) {
        if(!socket.username) {
            return;
        }

        usernames.splice(usernames.indexOf(socket.username), 1);
        updateUserNames();
    });
});


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

using Microsoft.Azure.Management.DataFactories.Conversion;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;

namespace Microsoft.Azure.Management.DataFactories.Runtime
{
    internal sealed class ActivityConfigurationConverter : JsonConverter
    {
        private const string TableToken = "table";
        private const string LinkedServiceToken = "linkedService";
        private const string PipelineToken = "pipeline";
        private const string InputsToken = "inputs";
        private const string OutputsToken = "outputs";

        private TableConverter tableConverter;
        private LinkedServiceConverter linkedServiceConverter;
        private PipelineConverter pipelineConverter;

        public ActivityConfigurationConverter()
        {
            tableConverter = new TableConverter();
            linkedServiceConverter = new LinkedServiceConverter();
            pipelineConverter = new PipelineConverter();
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(ActivityConfiguration);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Collection<ResolvedTable> inputs = new Collection<ResolvedTable>();
            Collection<ResolvedTable> outputs = new Collection<ResolvedTable>();

            ActivityConfiguration activityConfiguration = new ActivityConfiguration();

            JObject jObject = JObject.Load(reader);
            JToken inputsJToken;
            JToken outputsJToken;
            JToken pipelineJToken;

            if (jObject.TryGetValue(InputsToken, StringComparison.OrdinalIgnoreCase, out inputsJToken))
            {
                activityConfiguration.Inputs = inputs;
                foreach (JObject resolvedTable in inputsJToken.Children<JObject>())
                {
                    inputs.Add(GetResolvedTable(resolvedTable));
                }
            }

            if (jObject.TryGetValue(OutputsToken, StringComparison.OrdinalIgnoreCase, out outputsJToken))
            {
                activityConfiguration.Outputs = outputs;
                foreach (JObject resolvedTable in outputsJToken.Children<JObject>())
                {
                    outputs.Add(GetResolvedTable(resolvedTable));
                }
            }

            if (jObject.TryGetValue(PipelineToken, StringComparison.OrdinalIgnoreCase, out pipelineJToken))
            {
                activityConfiguration.Pipeline = GetPipeline(pipelineJToken);
            }

            return activityConfiguration;
        }

        private ResolvedTable GetResolvedTable(JObject jObject)
        {
            ResolvedTable resolvedTable = new ResolvedTable();

            JToken tableJToken;
            JToken linkedServiceJToken;

            if (jObject.TryGetValue(TableToken, StringComparison.OrdinalIgnoreCase, out tableJToken))
            {
                Core.Models.Table internalTable = Core.DataFactoryManagementClient.DeserializeInternalTableJson(tableJToken.ToString());
                resolvedTable.Table = tableConverter.ToWrapperType(internalTable);
            }

            if (jObject.TryGetValue(LinkedServiceToken, StringComparison.OrdinalIgnoreCase, out linkedServiceJToken))
            {
                Core.Models.LinkedService internalLinkedService = Core.DataFactoryManagementClient.DeserializeInternalLinkedServiceJson(linkedServiceJToken.ToString());
                resolvedTable.LinkedService = linkedServiceConverter.ToWrapperType(internalLinkedService);
            }

            return resolvedTable;
        }

        private Models.Pipeline GetPipeline(JToken jToken)
        {
            Core.Models.Pipeline internalPipeline = Core.DataFactoryManagementClient.DeserializeInternalPipelineJson(jToken.ToString());
            return pipelineConverter.ToWrapperType(internalPipeline);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}


text:
from os.path import join, dirname, abspath, isabs

try:
    import cv
except ImportError:
    import cv2.cv as cv

from thumbor.point import FocalPoint
from thumbor.detectors import BaseDetector

class CascadeLoaderDetector(BaseDetector):

    def load_cascade_file(self, module_path, cascade_file_path):
        if not hasattr(self.__class__, 'cascade'):
            if isabs(cascade_file_path):
                cascade_file = cascade_file_path
            else:
                cascade_file = join(abspath(dirname(module_path)), cascade_file_path)
            self.__class__.cascade = cv.Load(cascade_file)

    def get_min_size_for(self, size):
        ratio = int(min(size) / 15)
        ratio = max(20, ratio)
        return (ratio, ratio)

    def get_features(self):
        engine = self.context.modules.engine

        mode, converted_image = engine.image_data_as_rgb(False)
        size = engine.size

        image = cv.CreateImageHeader(size, cv.IPL_DEPTH_8U, 3)
        cv.SetData(image, converted_image)

        gray = cv.CreateImage(size, 8, 1)
        convert_mode = getattr(cv, 'CV_%s2GRAY' % mode)
        cv.CvtColor(image, gray, convert_mode)

        min_size = self.get_min_size_for(size)
        haar_scale = 1.2
        min_neighbors = 3

        cv.EqualizeHist(gray, gray)

        faces = cv.HaarDetectObjects(
            gray,
            self.__class__.cascade, cv.CreateMemStorage(0),
            haar_scale, min_neighbors,
            cv.CV_HAAR_DO_CANNY_PRUNING, min_size)

        faces_scaled = []

        for ((x, y, w, h), n) in faces:
            # the input to cv.HaarDetectObjects was resized, so scale the
            # bounding box of each face and convert it to two CvPoints
            x2, y2 = (x + w), (y + h)
            faces_scaled.append(((x, y, x2 - x, y2 - y), n))

        return faces_scaled

    def detect(self, callback):
        features = self.get_features()

        if features:
            for square, neighbors in features:
                self.context.request.focal_points.append(FocalPoint.from_square(*square))
            callback()
        else:
            self.next(callback)


text:
/*
Title: Tutorials
Description: Learn how to make your own bot!
Date: July 24, 2015
Tags: machine learning,nlp,language,processing,opencv
*/

![Man, presumably reading a Twitterbot tutorial](/content/images/illustrations/man-reading-mail-768.jpg){.float-right}

To make good bots, you need a **little bit of software** (preferably free and [open source](https://en.wikipedia.org/wiki/Open-source_software)), [**some useful data**](/resources) to connect the bot to, and **tutorials and [articles](/articles)** to explain how to connect it all together.

Many people provide these resources **for free** -- and **Botwiki.org** collects them. If you find anything useful, be sure to thank the person through their website, an email or social media site of their choice :-)

### General tutorials
- [Basic Twitter bot etiquette](basic-twitter-bot-etiquette-tiny-subversions) -- by [Darius Kazemi](https://twitter.com/tinysubversions), applies to *all* bots
- [Bots Should Punch Up](bots-should-punch-up) -- by [Leonard Richardson](http://www.crummy.com/)

### Technical tutorials

- [Machine learning cheat sheet map](http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html) -- "choosing the right estimator"
- [OpenCV tutorials](http://docs.opencv.org/doc/tutorials/tutorials.html)
- [Intro to NLP with spaCy](http://nicschrading.com/project/Intro-to-NLP-with-spaCy/) -- "an introduction to spaCy for natural language processing and machine learning with special help from Scikit-learn"

### Network-specific tutorials
- [Tutorials for Twitter bots](twitterbots)
- [Tutorials for Slack bots](slackbots)
- [Tutorials for IRC bots](irc-bots)
- [Tutorials for Telegram bots](telegram-bots)

Also check out [the opensourced bots](/tag/opensource).


text:
Short programs written in Ruby:
- Deaf Grandma
- Pig Latin & RSpec
- SSN / Regular Expressions Drill
- Shuffle
- Factorials using both iteration and recursion
- Anagram generator
- Prime Factors


text:
WELCOME to Sh@reBox!!

 Signup or Login

      <carousel interval="myInterval" no-wrap="noWrapSlides">
        <slide ng-repeat="slide in slides" active="slide.active">

        </slide>
      </carousel>


text:
.class Lcom/android/internal/telephony/ADNRecordLoader;
.super Landroid/os/Handler;
.source "HtcAdnRecord.java"

# static fields
.field static final EVENT_ADN_LOAD_ALL_DONE:I = 0x1

.field static final EVENT_EF_LINEAR_RECORD_SIZE_DONE:I = 0x2

.field static final EVENT_EXT_RECORD_UPDATE:I = 0x4

.field static final EVENT_UPDATE_RECORD_DONE:I = 0x3

.field static final LOG_TAG:Ljava/lang/String; = "HtcADNRecord"

# instance fields
.field adnList:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Lcom/android/internal/telephony/HtcAdnRecord;",
            ">;"
        }
    .end annotation
.end field

.field ef:I

.field mExt1List:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Lcom/android/internal/telephony/HtcExt1Record;",
            ">;"
        }
    .end annotation
.end field

.field private mIccFileHandler:Lcom/android/internal/telephony/IccFileHandler;

.field phone:Lcom/android/internal/telephony/PhoneBase;

.field recordNumber:I

.field result:Ljava/lang/Object;

.field userResponse:Landroid/os/Message;

# direct methods
.method constructor <init>(Ljava/util/ArrayList;Lcom/android/internal/telephony/PhoneBase;)V
    .locals 1
    .parameter
    .parameter "phone"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/ArrayList",
            "<",
            "Lcom/android/internal/telephony/HtcExt1Record;",
            ">;",
            "Lcom/android/internal/telephony/PhoneBase;",
            ")V"
        }
    .end annotation

    .prologue
    .line 65
    .local p1, ext1List:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Lcom/android/internal/telephony/HtcExt1Record;>;"
    invoke-virtual {p2}, Lcom/android/internal/telephony/PhoneBase;->getHandler()Landroid/os/Handler;

    move-result-object v0

    invoke-virtual {v0}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v0

    invoke-direct {p0, v0}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    .line 45
    const/16 v0, 0x32

    iput v0, p0, Lcom/android/internal/telephony/ADNRecordLoader;->ef:I

    .line 66
    iput-object p2, p0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    .line 67
    iput-object p1, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    .line 68
    return-void
.end method

.method constructor <init>(Ljava/util/ArrayList;Lcom/android/internal/telephony/PhoneBase;Lcom/android/internal/telephony/IccFileHandler;)V
    .locals 1
    .parameter
    .parameter "phone"
    .parameter "iccFileHandler"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/ArrayList",
            "<",
            "Lcom/android/internal/telephony/HtcExt1Record;",
            ">;",
            "Lcom/android/internal/telephony/PhoneBase;",
            "Lcom/android/internal/telephony/IccFileHandler;",
            ")V"
        }
    .end annotation

    .prologue
    .line 74
    .local p1, ext1List:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Lcom/android/internal/telephony/HtcExt1Record;>;"
    invoke-virtual {p2}, Lcom/android/internal/telephony/PhoneBase;->getHandler()Landroid/os/Handler;

    move-result-object v0

    invoke-virtual {v0}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v0

    invoke-direct {p0, v0}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    .line 45
    const/16 v0, 0x32

    iput v0, p0, Lcom/android/internal/telephony/ADNRecordLoader;->ef:I

    .line 75
    iput-object p2, p0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    .line 76
    iput-object p1, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    .line 77
    iput-object p3, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mIccFileHandler:Lcom/android/internal/telephony/IccFileHandler;

    .line 78
    return-void
.end method

.method private getIccFileHandler()Lcom/android/internal/telephony/IccFileHandler;
    .locals 2

    .prologue
    .line 81
    iget-object v0, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mIccFileHandler:Lcom/android/internal/telephony/IccFileHandler;

    if-eqz v0, :cond_0

    .line 82
    iget-object v0, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mIccFileHandler:Lcom/android/internal/telephony/IccFileHandler;

    .line 84
    :goto_0
    return-object v0

    :cond_0
    iget-object v0, p0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    iget-object v1, p0, Lcom/android/internal/telephony/ADNRecordLoader;->mIccFileHandler:Lcom/android/internal/telephony/IccFileHandler;

    invoke-virtual {v0, v1}, Lcom/android/internal/telephony/PhoneBase;->getIccFileHandler(Lcom/android/internal/telephony/IccFileHandler;)Lcom/android/internal/telephony/IccFileHandler;

    move-result-object v0

    goto :goto_0
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 17
    .parameter "msg"

    .prologue
    .line 143
    :try_start_0
    move-object/from16 v0, p1

    iget v2, v0, Landroid/os/Message;->what:I
    :try_end_0
    .catch Ljava/lang/RuntimeException; {:try_start_0 .. :try_end_0} :catch_0

    packed-switch v2, :pswitch_data_0

    .line 267
    :cond_0
    :goto_0
    :pswitch_0
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    if-eqz v2, :cond_1

    .line 268
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    invoke-static {v2}, Landroid/os/AsyncResult;->forMessage(Landroid/os/Message;)Landroid/os/AsyncResult;

    move-result-object v2

    move-object/from16 v0, p0

    iget-object v3, v0, Lcom/android/internal/telephony/ADNRecordLoader;->result:Ljava/lang/Object;

    iput-object v3, v2, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    .line 269
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    invoke-virtual {v2}, Landroid/os/Message;->sendToTarget()V

    .line 270
    const/4 v2, 0x0

    move-object/from16 v0, p0

    iput-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    .line 272
    :cond_1
    :goto_1
    return-void

    .line 148
    :pswitch_1
    :try_start_1
    const-string v2, "HtcADNRecord"

    const-string v3, "EVENT_EF_LINEAR_RECORD_SIZE_DONE"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 149
    move-object/from16 v0, p1

    iget-object v2, v0, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v2, Landroid/os/AsyncResult;

    move-object v0, v2

    check-cast v0, Landroid/os/AsyncResult;

    move-object v8, v0

    .line 150
    .local v8, ar:Landroid/os/AsyncResult;
    iget-object v2, v8, Landroid/os/AsyncResult;->userObj:Ljava/lang/Object;

    check-cast v2, Lcom/android/internal/telephony/HtcAdnRecord;

    move-object v0, v2

    check-cast v0, Lcom/android/internal/telephony/HtcAdnRecord;

    move-object v7, v0

    .line 152
    .local v7, adnRecord:Lcom/android/internal/telephony/HtcAdnRecord;
    iget-object v2, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-eqz v2, :cond_2

    .line 153
    new-instance v2, Ljava/lang/RuntimeException;

    const-string v3, "get EF record size failed"

    iget-object v5, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-direct {v2, v3, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v2
    :try_end_1
    .catch Ljava/lang/RuntimeException; {:try_start_1 .. :try_end_1} :catch_0

    .line 256
    .end local v7           #adnRecord:Lcom/android/internal/telephony/HtcAdnRecord;
    .end local v8           #ar:Landroid/os/AsyncResult;
    :catch_0
    move-exception v10

    .line 257
    .local v10, exc:Ljava/lang/RuntimeException;
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    if-eqz v2, :cond_1

    .line 258
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    invoke-static {v2}, Landroid/os/AsyncResult;->forMessage(Landroid/os/Message;)Landroid/os/AsyncResult;

    move-result-object v2

    iput-object v10, v2, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    .line 259
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    invoke-virtual {v2}, Landroid/os/Message;->sendToTarget()V

    .line 262
    const/4 v2, 0x0

    move-object/from16 v0, p0

    iput-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    goto :goto_1

    .line 157
    .end local v10           #exc:Ljava/lang/RuntimeException;
    .restart local v7       #adnRecord:Lcom/android/internal/telephony/HtcAdnRecord;
    .restart local v8       #ar:Landroid/os/AsyncResult;
    :cond_2
    :try_start_2
    iget-object v2, v8, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v2, [I

    move-object v0, v2

    check-cast v0, [I

    move-object v15, v0

    .line 163
    .local v15, recordSize:[I
    array-length v2, v15

    const/4 v3, 0x3

    if-ne v2, v3, :cond_3

    move-object/from16 v0, p0

    iget v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->recordNumber:I

    const/4 v3, 0x2

    aget v3, v15, v3

    if-le v2, v3, :cond_4

    .line 164
    :cond_3
    new-instance v2, Ljava/lang/RuntimeException;

    const-string v3, "get wrong EF record size format"

    iget-object v5, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-direct {v2, v3, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v2

    .line 168
    :cond_4
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    const/4 v3, 0x0

    aget v3, v15, v3

    invoke-virtual {v7, v2, v3}, Lcom/android/internal/telephony/HtcAdnRecord;->buildAdnString(Ljava/util/ArrayList;I)[B

    move-result-object v4

    .line 170
    .local v4, data:[B
    if-nez v4, :cond_5

    .line 171
    new-instance v2, Ljava/lang/RuntimeException;

    const-string v3, "worong IAP format"

    iget-object v5, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-direct {v2, v3, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v2

    .line 177
    :cond_5
    invoke-direct/range {p0 .. p0}, Lcom/android/internal/telephony/ADNRecordLoader;->getIccFileHandler()Lcom/android/internal/telephony/IccFileHandler;

    move-result-object v1

    .line 178
    .local v1, iccFileHander:Lcom/android/internal/telephony/IccFileHandler;
    if-eqz v1, :cond_6

    .line 179
    move-object/from16 v0, p0

    iget v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->ef:I

    move-object/from16 v0, p0

    iget v3, v0, Lcom/android/internal/telephony/ADNRecordLoader;->recordNumber:I

    const/4 v5, 0x0

    const/4 v6, 0x3

    move-object/from16 v0, p0

    invoke-virtual {v0, v6}, Lcom/android/internal/telephony/ADNRecordLoader;->obtainMessage(I)Landroid/os/Message;

    move-result-object v6

    invoke-virtual/range {v1 .. v6}, Lcom/android/internal/telephony/IccFileHandler;->updateEFLinearFixed(II[BLjava/lang/String;Landroid/os/Message;)V

    goto/16 :goto_0

    .line 182
    :cond_6
    const-string v2, "HtcADNRecord"

    const-string v3, "mIccFileHandler is null"

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto/16 :goto_0

    .line 189
    .end local v1           #iccFileHander:Lcom/android/internal/telephony/IccFileHandler;
    .end local v4           #data:[B
    .end local v7           #adnRecord:Lcom/android/internal/telephony/HtcAdnRecord;
    .end local v8           #ar:Landroid/os/AsyncResult;
    .end local v15           #recordSize:[I
    :pswitch_2
    const-string v2, "HtcADNRecord"

    const-string v3, "EVENT_UPDATE_RECORD_DONE"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 190
    move-object/from16 v0, p1

    iget-object v2, v0, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v2, Landroid/os/AsyncResult;

    move-object v0, v2

    check-cast v0, Landroid/os/AsyncResult;

    move-object v8, v0

    .line 192
    .restart local v8       #ar:Landroid/os/AsyncResult;
    iget-object v2, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-eqz v2, :cond_7

    .line 193
    new-instance v2, Ljava/lang/RuntimeException;

    const-string v3, "update EF IAP record failed"

    iget-object v5, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-direct {v2, v3, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v2

    .line 196
    :cond_7
    const/4 v2, 0x0

    move-object/from16 v0, p0

    iput-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->result:Ljava/lang/Object;

    goto/16 :goto_0

    .line 206
    .end local v8           #ar:Landroid/os/AsyncResult;
    :pswitch_3
    const-string v2, "HtcADNRecord"

    const-string v3, "EVENT_ADN_LOAD_ALL_DONE"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 208
    move-object/from16 v0, p1

    iget-object v2, v0, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v2, Landroid/os/AsyncResult;

    move-object v0, v2

    check-cast v0, Landroid/os/AsyncResult;

    move-object v8, v0

    .line 209
    .restart local v8       #ar:Landroid/os/AsyncResult;
    iget-object v2, v8, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v2, Ljava/util/ArrayList;

    move-object v0, v2

    check-cast v0, Ljava/util/ArrayList;

    move-object v9, v0

    .line 211
    .local v9, datas:Ljava/util/ArrayList;,"Ljava/util/ArrayList<[B>;"
    iget-object v2, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-eqz v2, :cond_8

    .line 212
    new-instance v2, Ljava/lang/RuntimeException;

    const-string v3, "load failed"

    iget-object v5, v8, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-direct {v2, v3, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v2

    .line 215
    :cond_8
    new-instance v2, Ljava/util/ArrayList;

    invoke-virtual {v9}, Ljava/util/ArrayList;->size()I

    move-result v3

    invoke-direct {v2, v3}, Ljava/util/ArrayList;-><init>(I)V

    move-object/from16 v0, p0

    iput-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->adnList:Ljava/util/ArrayList;

    .line 216
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->adnList:Ljava/util/ArrayList;

    move-object/from16 v0, p0

    iput-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->result:Ljava/lang/Object;

    .line 218
    const/4 v13, 0x0

    .local v13, i:I
    invoke-virtual {v9}, Ljava/util/ArrayList;->size()I

    move-result v16

    .local v16, s:I
    :goto_2
    move/from16 v0, v16

    if-ge v13, v0, :cond_0

    .line 219
    new-instance v7, Lcom/android/internal/telephony/HtcAdnRecord;

    add-int/lit8 v3, v13, 0x1

    invoke-virtual {v9, v13}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, [B

    invoke-direct {v7, v3, v2}, Lcom/android/internal/telephony/HtcAdnRecord;-><init>(I[B)V

    .line 220
    .restart local v7       #adnRecord:Lcom/android/internal/telephony/HtcAdnRecord;
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->adnList:Ljava/util/ArrayList;

    invoke-virtual {v2, v7}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    .line 222
    if-nez v13, :cond_a

    .line 223
    invoke-virtual {v9, v13}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, [B

    array-length v14, v2

    .line 225
    .local v14, maxAlphaTagLength:I
    const/16 v2, 0xe

    if-ge v14, v2, :cond_c

    const/4 v14, 0x0

    .line 229
    :goto_3
    invoke-static {}, Lcom/htc/service/HtcTelephonyManager;->dualPhoneEnable()Z

    move-result v2

    if-nez v2, :cond_9

    invoke-static {}, Lcom/htc/service/HtcTelephonyManager;->dualGSMPhoneEnable()Z

    move-result v2

    if-eqz v2, :cond_f

    .line 230
    :cond_9
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v2}, Lcom/android/internal/telephony/PhoneBase;->getPhoneType()I

    move-result v2

    const/4 v3, 0x1

    if-ne v2, v3, :cond_d

    .line 231
    const-string v2, "gsm.sim.alpha-tag.length"

    invoke-static {v14}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    .line 244
    .end local v14           #maxAlphaTagLength:I
    :cond_a
    :goto_4
    invoke-virtual {v7}, Lcom/android/internal/telephony/HtcAdnRecord;->hasExtendedRecord()Z

    move-result v2

    if-eqz v2, :cond_b

    .line 245
    iget v12, v7, Lcom/android/internal/telephony/HtcAdnRecord;->extRecord:I

    .line 246
    .local v12, extindex:I
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    if-eqz v2, :cond_b

    .line 247
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    invoke-virtual {v2}, Ljava/util/ArrayList;->size()I

    move-result v2

    if-gt v12, v2, :cond_b

    .line 248
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->mExt1List:Ljava/util/ArrayList;

    add-int/lit8 v3, v12, -0x1

    invoke-virtual {v2, v3}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v11

    check-cast v11, Lcom/android/internal/telephony/HtcExt1Record;

    .line 249
    .local v11, ext1Record:Lcom/android/internal/telephony/HtcExt1Record;
    invoke-virtual {v11}, Lcom/android/internal/telephony/HtcExt1Record;->getBytes()[B

    move-result-object v2

    invoke-virtual {v7, v2}, Lcom/android/internal/telephony/HtcAdnRecord;->appendExtRecord([B)V

    .line 218
    .end local v11           #ext1Record:Lcom/android/internal/telephony/HtcExt1Record;
    .end local v12           #extindex:I
    :cond_b
    add-int/lit8 v13, v13, 0x1

    goto :goto_2

    .line 225
    .restart local v14       #maxAlphaTagLength:I
    :cond_c
    add-int/lit8 v14, v14, -0xe

    goto :goto_3

    .line 232
    :cond_d
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v2}, Lcom/android/internal/telephony/PhoneBase;->getPhoneType()I

    move-result v2

    const/4 v3, 0x5

    if-ne v2, v3, :cond_e

    .line 233
    const-string v2, "gsm.sub.icc.alpha-tag.length"

    invoke-static {v14}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    goto :goto_4

    .line 234
    :cond_e
    move-object/from16 v0, p0

    iget-object v2, v0, Lcom/android/internal/telephony/ADNRecordLoader;->phone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v2}, Lcom/android/internal/telephony/PhoneBase;->getPhoneType()I

    move-result v2

    const/4 v3, 0x2

    if-ne v2, v3, :cond_a

    .line 235
    const-string v2, "cdma.sim.alpha-tag.length"

    invoke-static {v14}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    goto :goto_4

    .line 238
    :cond_f
    const-string v2, "gsm.usim.alpha-tag.length"

    invoke-static {v14}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V
    :try_end_2
    .catch Ljava/lang/RuntimeException; {:try_start_2 .. :try_end_2} :catch_0

    goto :goto_4

    .line 143
    nop

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_3
        :pswitch_1
        :pswitch_2
        :pswitch_0
    .end packed-switch
.end method

.method loadAllFromEF(ILandroid/os/Message;)V
    .locals 3
    .parameter "efid"
    .parameter "response"

    .prologue
    .line 90
    iput p1, p0, Lcom/android/internal/telephony/ADNRecordLoader;->ef:I

    .line 91
    iput-object p2, p0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    .line 94
    invoke-direct {p0}, Lcom/android/internal/telephony/ADNRecordLoader;->getIccFileHandler()Lcom/android/internal/telephony/IccFileHandler;

    move-result-object v0

    .line 95
    .local v0, iccFileHander:Lcom/android/internal/telephony/IccFileHandler;
    if-eqz v0, :cond_0

    .line 96
    const/4 v1, 0x1

    invoke-virtual {p0, v1}, Lcom/android/internal/telephony/ADNRecordLoader;->obtainMessage(I)Landroid/os/Message;

    move-result-object v1

    invoke-virtual {v0, p1, v1}, Lcom/android/internal/telephony/IccFileHandler;->loadEFLinearFixedAll(ILandroid/os/Message;)V

    .line 102
    :goto_0
    return-void

    .line 98
    :cond_0
    const-string v1, "HtcADNRecord"

    const-string v2, "mIccFileHandler is null"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method updateEF(IILcom/android/internal/telephony/HtcAdnRecord;Landroid/os/Message;)V
    .locals 3
    .parameter "efid"
    .parameter "recordNumber"
    .parameter "adnRecord"
    .parameter "response"

    .prologue
    .line 119
    iput p1, p0, Lcom/android/internal/telephony/ADNRecordLoader;->ef:I

    .line 120
    iput p2, p0, Lcom/android/internal/telephony/ADNRecordLoader;->recordNumber:I

    .line 121
    iput-object p4, p0, Lcom/android/internal/telephony/ADNRecordLoader;->userResponse:Landroid/os/Message;

    .line 125
    invoke-direct {p0}, Lcom/android/internal/telephony/ADNRecordLoader;->getIccFileHandler()Lcom/android/internal/telephony/IccFileHandler;

    move-result-object v0

    .line 126
    .local v0, iccFileHander:Lcom/android/internal/telephony/IccFileHandler;
    if-eqz v0, :cond_0

    .line 127
    const/4 v1, 0x2

    invoke-virtual {p0, v1, p3}, Lcom/android/internal/telephony/ADNRecordLoader;->obtainMessage(ILjava/lang/Object;)Landroid/os/Message;

    move-result-object v1

    invoke-virtual {v0, p1, v1}, Lcom/android/internal/telephony/IccFileHandler;->getEFLinearRecordSize(ILandroid/os/Message;)V

    .line 133
    :goto_0
    return-void

    .line 130
    :cond_0
    const-string v1, "HtcADNRecord"

    const-string v2, "mIccFileHandler is null"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method


text:
{{ partial "header.html" . }}

            <meta itemprop="mainEntityOfPage"  itemType="https://schema.org/WebPage" content="{{ .Site.BaseURL }}"/>
            <meta itemprop="dateModified" content="{{ .Date.Format "2006-01-02T15:04:05-07:00" }}">
            <meta itemprop="headline" content="{{ .Title }}">
            <meta itemprop="description" content="{{ .Summary }}">
            <meta itemprop="url" content="{{ .Permalink }}">

                <meta itemprop="url" content="{{ $.Site.BaseURL }}images/{{ with .Params.image }}{{ . }}{{ else }}default.jpg{{ end }}" />
                <meta itemprop="width" content="800">
                <meta itemprop="height" content="800">

                    <meta itemprop="url" content="{{ .Site.BaseURL }}images/logo.jpg">
                    <meta itemprop="width" content="100">
                    <meta itemprop="height" content="100">

                <meta itemprop="name" content="{{ .Site.Title }}">

                <meta itemprop="name" content="{{ .Site.Params.Author }}">

{{ .Title }}

                {{ if not .Date.IsZero }}
                <time itemprop="datePublished" pubdate="pubdate" datetime="{{ .Date.Format "2006-01-02T15:04:05-07:00" }}"> Posted on {{ .Date.Format "January 2, 2006" }}</time>
                {{ end }}

                {{ with .Params.tags }} {{ range . }}{{ . }} {{ end }}{{ end }}

{{ .Content }}

    {{ partial "sidebar.html" . }}

{{ partial "footer.html" . }}


text:
<?php

namespace Phalcon\Mvc;

/**
 * Phalcon\Mvc\UrlInterface
 * Interface for Phalcon\Mvc\UrlInterface
 */
interface UrlInterface
{

    /**
     * Sets a prefix to all the urls generated
     *
     * @param string $baseUri
     */
    public function setBaseUri($baseUri);

    /**
     * Returns the prefix for all the generated urls. By default /
     *
     * @return string
     */
    public function getBaseUri();

    /**
     * Sets a base paths for all the generated paths
     *
     * @param string $basePath
     */
    public function setBasePath($basePath);

    /**
     * Returns a base path
     *
     * @return string
     */
    public function getBasePath();

    /**
     * Generates a URL
     *
     * @param string|array $uri
     * @param array|object $args Optional arguments to be appended to the query string
     * @param bool $local
     * @param bool $$local
     * @return string
     */
    public function get($uri = null, $args = null, $local = null);

    /**
     * Generates a local path
     *
     * @param string $path
     * @return string
     */
    public function path($path = null);

}


text:
""" Handles logic for individual trades, including safety features (e.g. stop loss)

Copyright (c) Cambridge Quantum Computing ltd. All rights reserved.
Licensed under the MIT License. See LICENSE file
in the project root for full license information.

"""
import sys
import datetime
from .loggable import Loggable
class TradeMonitor(Loggable):
    """ Used for monitoring open positions and determining when it is time to
    close them. This could be due to a timed position of n minutes, or because
    of a stop loss, or any monitoring tactic you want. """
    def notify_single(self, trade, current_bar):
        """ Monitor a single trade given the current bar. This is useful for
        checking trade-specific metrics such as the current return or trading
        length. True is returned if the trade should remain open, False if it
        should be closed.
        """
        return True

    def notify_multiple(self, open_trades, closed_trades, current_bar):
        """ Monitor all trades opened so far, including closed trades.
        This is useful for multi-trade metrics, such as the overall return
        so far in the day (e.g. for a daily stoploss to shut down all open
        trades).
        """
        raise NotImplementedError("Multiple trade monitoring is not yet implemented")

    def getLogTag(self):
        return self.__class__.__name__

class MultiTradeMonitor(TradeMonitor):
    def __init__(self, child_trade_monitors):
        self.child_trade_monitors = child_trade_monitors
    def notify_single(self, trade, current_bar):
        """ Run the child monitors on the trades. If one closes an order,
        it should return False to prevent other monitors from wasting time
        on it. """
        for monitor in self.child_trade_monitors:
            if not monitor.notify_single(trade, current_bar):
                return False
            return True
    def notify_multiple(self, open_trades, closed_trades, current_bar):
        for monitor in self.child_trade_monitors:
            monitor.notify_multiple(open_trades, closed_trades, current_bar)

class NullTradeMonitor(TradeMonitor):
    pass

class BoundaryTradeMonitor(TradeMonitor):
    def __init__(self, stop_loss_bp=None, take_profit_bp=None):
        self.stop_loss_bp = stop_loss_bp
        self.take_profit_bp = take_profit_bp
    def notify_single(self, trade, current_bar):
        current_return_bp = ((current_bar.close / trade.close_price) - 1) * 10000
        if -current_return_bp > self.stop_loss_bp:
            #fire stop loss
            self.report("Stop loss triggered")
            return False
        elif current_return_bp > self.take_profit_bp:
            self.report("Take profit triggered")
            return False
        return True

class TimeLimitTradeMonitor(TradeMonitor):
    def __init__(self, time_limit):
        self.timedelta = datetime.timedelta(minutes=time_limit)
    def notify_single(self, trade, current_bar):
        if trade.open_time + self.timedelta >= current_bar.time:
            self.report("Time limit triggered")
            return False
        return True


text:
package kafka.server.metadata

import java.util.Properties
import java.util.concurrent.atomic.AtomicLong
import kafka.coordinator.group.GroupCoordinator
import kafka.coordinator.transaction.TransactionCoordinator
import kafka.log.{LogManager, UnifiedLog}
import kafka.server.ConfigAdminManager.toLoggableProps
import kafka.server.{ConfigEntityName, ConfigHandler, ConfigType, KafkaConfig, ReplicaManager, RequestLocal}
import kafka.utils.Logging
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.config.ConfigResource.Type.{BROKER, TOPIC}
import org.apache.kafka.common.internals.Topic
import org.apache.kafka.image.{MetadataDelta, MetadataImage, TopicDelta, TopicsImage}
import org.apache.kafka.metadata.authorizer.ClusterMetadataAuthorizer
import org.apache.kafka.server.authorizer.Authorizer
import org.apache.kafka.server.fault.FaultHandler

import scala.collection.mutable

object BrokerMetadataPublisher extends Logging {
  /**
   * Given a topic name, find out if it changed. Note: if a topic named X was deleted and
   * then re-created, this method will return just the re-creation. The deletion will show
   * up in deletedTopicIds and must be handled separately.
   *
   * @param topicName   The topic name.
   * @param newImage    The new metadata image.
   * @param delta       The metadata delta to search.
   *
   * @return            The delta, or None if appropriate.
   */
  def getTopicDelta(topicName: String,
                    newImage: MetadataImage,
                    delta: MetadataDelta): Option[TopicDelta] = {
    Option(newImage.topics().getTopic(topicName)).flatMap {
      topicImage => Option(delta.topicsDelta()).flatMap {
        topicDelta => Option(topicDelta.changedTopic(topicImage.id()))
      }
    }
  }

  /**
   * Find logs which should not be on the current broker, according to the metadata image.
   *
   * @param brokerId        The ID of the current broker.
   * @param newTopicsImage  The new topics image after broker has been reloaded
   * @param logs            A collection of Log objects.
   *
   * @return          The topic partitions which are no longer needed on this broker.
   */
  def findStrayPartitions(brokerId: Int,
                          newTopicsImage: TopicsImage,
                          logs: Iterable[UnifiedLog]): Iterable[TopicPartition] = {
    logs.flatMap { log =>
      val topicId = log.topicId.getOrElse {
        throw new RuntimeException(s"The log dir $log does not have a topic ID, " +
          "which is not allowed when running in KRaft mode.")
      }

      val partitionId = log.topicPartition.partition()
      Option(newTopicsImage.getPartition(topicId, partitionId)) match {
        case Some(partition) =>
          if (!partition.replicas.contains(brokerId)) {
            info(s"Found stray log dir $log: the current replica assignment ${partition.replicas} " +
              s"does not contain the local brokerId $brokerId.")
            Some(log.topicPartition)
          } else {
            None
          }

        case None =>
          info(s"Found stray log dir $log: the topicId $topicId does not exist in the metadata image")
          Some(log.topicPartition)
      }
    }
  }
}

class BrokerMetadataPublisher(
  conf: KafkaConfig,
  metadataCache: KRaftMetadataCache,
  logManager: LogManager,
  replicaManager: ReplicaManager,
  groupCoordinator: GroupCoordinator,
  txnCoordinator: TransactionCoordinator,
  clientQuotaMetadataManager: ClientQuotaMetadataManager,
  dynamicConfigHandlers: Map[String, ConfigHandler],
  private val _authorizer: Option[Authorizer],
  fatalFaultHandler: FaultHandler,
  metadataPublishingFaultHandler: FaultHandler
) extends MetadataPublisher with Logging {
  logIdent = s"[BrokerMetadataPublisher id=${conf.nodeId}] "

  import BrokerMetadataPublisher._

  /**
   * The broker ID.
   */
  val brokerId: Int = conf.nodeId

  /**
   * True if this is the first time we have published metadata.
   */
  var _firstPublish = true

  /**
   * This is updated after all components (e.g. LogManager) has finished publishing the new metadata delta
   */
  val publishedOffsetAtomic = new AtomicLong(-1)

  override def publish(delta: MetadataDelta, newImage: MetadataImage): Unit = {
    val highestOffsetAndEpoch = newImage.highestOffsetAndEpoch()

    val deltaName = if (_firstPublish) {
      s"initial MetadataDelta up to ${highestOffsetAndEpoch.offset}"
    } else {
      s"MetadataDelta up to ${highestOffsetAndEpoch.offset}"
    }
    try {
      if (isTraceEnabled) {
        trace(s"Publishing delta $delta with highest offset $highestOffsetAndEpoch")
      }

      // Publish the new metadata image to the metadata cache.
      metadataCache.setImage(newImage)

      val metadataVersionLogMsg = s"metadata.version ${newImage.features().metadataVersion()}"

      if (_firstPublish) {
        info(s"Publishing initial metadata at offset $highestOffsetAndEpoch with $metadataVersionLogMsg.")

        // If this is the first metadata update we are applying, initialize the managers
        // first (but after setting up the metadata cache).
        initializeManagers()
      } else if (isDebugEnabled) {
        debug(s"Publishing metadata at offset $highestOffsetAndEpoch with $metadataVersionLogMsg.")
      }

      Option(delta.featuresDelta()).foreach { featuresDelta =>
        featuresDelta.metadataVersionChange().ifPresent{ metadataVersion =>
          info(s"Updating metadata.version to ${metadataVersion.featureLevel()} at offset $highestOffsetAndEpoch.")
        }
      }

      // Apply topic deltas.
      Option(delta.topicsDelta()).foreach { topicsDelta =>
        try {
          // Notify the replica manager about changes to topics.
          replicaManager.applyDelta(topicsDelta, newImage)
        } catch {
          case t: Throwable => metadataPublishingFaultHandler.handleFault("Error applying topics " +
            s"delta in ${deltaName}", t)
        }
        try {
          // Update the group coordinator of local changes
          updateCoordinator(newImage,
            delta,
            Topic.GROUP_METADATA_TOPIC_NAME,
            groupCoordinator.onElection,
            groupCoordinator.onResignation)
        } catch {
          case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating group " +
            s"coordinator with local changes in ${deltaName}", t)
        }
        try {
          // Update the transaction coordinator of local changes
          updateCoordinator(newImage,
            delta,
            Topic.TRANSACTION_STATE_TOPIC_NAME,
            txnCoordinator.onElection,
            txnCoordinator.onResignation)
        } catch {
          case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating txn " +
            s"coordinator with local changes in ${deltaName}", t)
        }
        try {
          // Notify the group coordinator about deleted topics.
          val deletedTopicPartitions = new mutable.ArrayBuffer[TopicPartition]()
          topicsDelta.deletedTopicIds().forEach { id =>
            val topicImage = topicsDelta.image().getTopic(id)
            topicImage.partitions().keySet().forEach {
              id => deletedTopicPartitions += new TopicPartition(topicImage.name(), id)
            }
          }
          if (deletedTopicPartitions.nonEmpty) {
            groupCoordinator.handleDeletedPartitions(deletedTopicPartitions, RequestLocal.NoCaching)
          }
        } catch {
          case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating group " +
            s"coordinator with deleted partitions in ${deltaName}", t)
        }
      }

      // Apply configuration deltas.
      Option(delta.configsDelta()).foreach { configsDelta =>
        configsDelta.changes().keySet().forEach { resource =>
          val props = newImage.configs().configProperties(resource)
          resource.`type`() match {
            case TOPIC =>
              try {
                // Apply changes to a topic's dynamic configuration.
                info(s"Updating topic ${resource.name()} with new configuration : " +
                  toLoggableProps(resource, props).mkString(","))
                dynamicConfigHandlers(ConfigType.Topic).
                  processConfigChanges(resource.name(), props)
              } catch {
                case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating topic " +
                  s"${resource.name()} with new configuration: ${toLoggableProps(resource, props).mkString(",")} " +
                  s"in ${deltaName}", t)
              }
            case BROKER =>
              if (resource.name().isEmpty) {
                try {
                  // Apply changes to "cluster configs" (also known as default BROKER configs).
                  // These are stored in KRaft with an empty name field.
                  info("Updating cluster configuration : " +
                    toLoggableProps(resource, props).mkString(","))
                  dynamicConfigHandlers(ConfigType.Broker).
                    processConfigChanges(ConfigEntityName.Default, props)
                } catch {
                  case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating " +
                    s"cluster with new configuration: ${toLoggableProps(resource, props).mkString(",")} " +
                    s"in ${deltaName}", t)
                }
              } else if (resource.name() == brokerId.toString) {
                try {
                  // Apply changes to this broker's dynamic configuration.
                  info(s"Updating broker $brokerId with new configuration : " +
                    toLoggableProps(resource, props).mkString(","))
                  dynamicConfigHandlers(ConfigType.Broker).
                    processConfigChanges(resource.name(), props)
                  // When applying a per broker config (not a cluster config), we also
                  // reload any associated file. For example, if the ssl.keystore is still
                  // set to /tmp/foo, we still want to reload /tmp/foo in case its contents
                  // have changed. This doesn't apply to topic configs or cluster configs.
                  reloadUpdatedFilesWithoutConfigChange(props)
                } catch {
                  case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating " +
                    s"broker with new configuration: ${toLoggableProps(resource, props).mkString(",")} " +
                    s"in ${deltaName}", t)
                }
              }
            case _ => // nothing to do
          }
        }
      }

      try {
        // Apply client quotas delta.
        Option(delta.clientQuotasDelta()).foreach { clientQuotasDelta =>
          clientQuotaMetadataManager.update(clientQuotasDelta)
        }
      } catch {
        case t: Throwable => metadataPublishingFaultHandler.handleFault("Error updating client " +
          s"quotas in ${deltaName}", t)
      }

      // Apply changes to ACLs. This needs to be handled carefully because while we are
      // applying these changes, the Authorizer is continuing to return authorization
      // results in other threads. We never want to expose an invalid state. For example,
      // if the user created a DENY ALL acl and then created an ALLOW ACL for topic foo,
      // we want to apply those changes in that order, not the reverse order! Otherwise
      // there could be a window during which incorrect authorization results are returned.
      Option(delta.aclsDelta()).foreach( aclsDelta =>
        _authorizer match {
          case Some(authorizer: ClusterMetadataAuthorizer) => if (aclsDelta.isSnapshotDelta) {
            try {
              // If the delta resulted from a snapshot load, we want to apply the new changes
              // all at once using ClusterMetadataAuthorizer#loadSnapshot. If this is the
              // first snapshot load, it will also complete the futures returned by
              // Authorizer#start (which we wait for before processing RPCs).
              authorizer.loadSnapshot(newImage.acls().acls())
            } catch {
              case t: Throwable => metadataPublishingFaultHandler.handleFault("Error loading " +
                s"authorizer snapshot in ${deltaName}", t)
            }
          } else {
            try {
              // Because the changes map is a LinkedHashMap, the deltas will be returned in
              // the order they were performed.
              aclsDelta.changes().entrySet().forEach(e =>
                if (e.getValue.isPresent) {
                  authorizer.addAcl(e.getKey, e.getValue.get())
                } else {
                  authorizer.removeAcl(e.getKey)
                })
            } catch {
              case t: Throwable => metadataPublishingFaultHandler.handleFault("Error loading " +
                s"authorizer changes in ${deltaName}", t)
            }
          }
          case _ => // No ClusterMetadataAuthorizer is configured. There is nothing to do.
        })

      if (_firstPublish) {
        finishInitializingReplicaManager(newImage)
      }
      publishedOffsetAtomic.set(newImage.highestOffsetAndEpoch().offset)
    } catch {
      case t: Throwable => metadataPublishingFaultHandler.handleFault("Uncaught exception while " +
        s"publishing broker metadata from ${deltaName}", t)
    } finally {
      _firstPublish = false
    }
  }

  override def publishedOffset: Long = publishedOffsetAtomic.get()

  def reloadUpdatedFilesWithoutConfigChange(props: Properties): Unit = {
    conf.dynamicConfig.reloadUpdatedFilesWithoutConfigChange(props)
  }

  /**
   * Update the coordinator of local replica changes: election and resignation.
   *
   * @param image latest metadata image
   * @param delta metadata delta from the previous image and the latest image
   * @param topicName name of the topic associated with the coordinator
   * @param election function to call on election; the first parameter is the partition id;
   *                 the second parameter is the leader epoch
   * @param resignation function to call on resignation; the first parameter is the partition id;
   *                    the second parameter is the leader epoch
   */
  def updateCoordinator(
    image: MetadataImage,
    delta: MetadataDelta,
    topicName: String,
    election: (Int, Int) => Unit,
    resignation: (Int, Option[Int]) => Unit
  ): Unit = {
    // Handle the case where the topic was deleted
    Option(delta.topicsDelta()).foreach { topicsDelta =>
      if (topicsDelta.topicWasDeleted(topicName)) {
        topicsDelta.image.getTopic(topicName).partitions.entrySet.forEach { entry =>
          if (entry.getValue.leader == brokerId) {
            resignation(entry.getKey, Some(entry.getValue.leaderEpoch))
          }
        }
      }
    }

    // Handle the case where the replica was reassigned, made a leader or made a follower
    getTopicDelta(topicName, image, delta).foreach { topicDelta =>
      val changes = topicDelta.localChanges(brokerId)

      changes.deletes.forEach { topicPartition =>
        resignation(topicPartition.partition, None)
      }
      changes.leaders.forEach { (topicPartition, partitionInfo) =>
        election(topicPartition.partition, partitionInfo.partition.leaderEpoch)
      }
      changes.followers.forEach { (topicPartition, partitionInfo) =>
        resignation(topicPartition.partition, Some(partitionInfo.partition.leaderEpoch))
      }
    }
  }

  private def initializeManagers(): Unit = {
    try {
      // Start log manager, which will perform (potentially lengthy)
      // recovery-from-unclean-shutdown if required.
      logManager.startup(metadataCache.getAllTopics())

      // Make the LogCleaner available for reconfiguration. We can't do this prior to this
      // point because LogManager#startup creates the LogCleaner object, if
      // log.cleaner.enable is true. TODO: improve this (see KAFKA-13610)
      Option(logManager.cleaner).foreach(conf.dynamicConfig.addBrokerReconfigurable)
    } catch {
      case t: Throwable => fatalFaultHandler.handleFault("Error starting LogManager", t)
    }
    try {
      // Start the replica manager.
      replicaManager.startup()
    } catch {
      case t: Throwable => fatalFaultHandler.handleFault("Error starting ReplicaManager", t)
    }
    try {
      // Start the group coordinator.
      groupCoordinator.startup(() => metadataCache.numPartitions(
        Topic.GROUP_METADATA_TOPIC_NAME).getOrElse(conf.offsetsTopicPartitions))
    } catch {
      case t: Throwable => fatalFaultHandler.handleFault("Error starting GroupCoordinator", t)
    }
    try {
      // Start the transaction coordinator.
      txnCoordinator.startup(() => metadataCache.numPartitions(
        Topic.TRANSACTION_STATE_TOPIC_NAME).getOrElse(conf.transactionTopicPartitions))
    } catch {
      case t: Throwable => fatalFaultHandler.handleFault("Error starting TransactionCoordinator", t)
    }
  }

  private def finishInitializingReplicaManager(newImage: MetadataImage): Unit = {
    try {
      // Delete log directories which we're not supposed to have, according to the
      // latest metadata. This is only necessary to do when we're first starting up. If
      // we have to load a snapshot later, these topics will appear in deletedTopicIds.
      val strayPartitions = findStrayPartitions(brokerId, newImage.topics, logManager.allLogs)
      if (strayPartitions.nonEmpty) {
        replicaManager.deleteStrayReplicas(strayPartitions)
      }
    } catch {
      case t: Throwable => metadataPublishingFaultHandler.handleFault("Error deleting stray " +
        "partitions during startup", t)
    }
    try {
      // Make sure that the high water mark checkpoint thread is running for the replica
      // manager.
      replicaManager.startHighWatermarkCheckPointThread()
    } catch {
      case t: Throwable => metadataPublishingFaultHandler.handleFault("Error starting high " +
        "watermark checkpoint thread during startup", t)
    }
}
}


text:
from mock import patch

from django.test import TestCase

from us_ignite.hubs import mailer

class TestNotifyRequest(TestCase):

    @patch('django.core.mail.mail_admins')
    def test_notification_is_sent_successfully(self, mock_mail):
        hub_request = object()
        mailer.notify_request(hub_request)
        mock_mail.assert_called_once()


text:
@interface UITextField (Extention)
+ (instancetype)searchBar;
@end


text:
package com.google.appengine.api.datastore.dev;

import com.google.appengine.api.datastore.Key;

/**
 * A policy for high replication job application. Implementations can decide whether or not a new
 * job should apply and whether or not a job that initially failed to apply should roll forward on
 * subsequent attempts.
 *
 *
Some implementation details that are pertinent to implementors of this interface:
 *
 *
When a user performs a non-transactional Put(), a non-transactional Delete(), or a Commit() of
 * a transaction to which at least one transactional Put() or Delete() was added, the {@link
 * LocalDatastoreService} attempts to apply that mutation using a job associated with the entity
 * group of the mutation. The decision of whether or not the job should apply is delegated to {@link
 * HighRepJobPolicy#shouldApplyNewJob(Key)}.
 *
 *
Unapplied jobs may be rolled forward in two ways: when the consistency model dictates it, and
 * when an entity group is groomed. We'll discuss these in turn.
 *
 *
When the high replication consistency model guarantees that users will see the most up-to-date
 * values for an entity group, we roll forward unapplied jobs before returning any data from the
 * entity group. Specifically, a transactional Get() will roll forward any unapplied jobs in the
 * entity group, as will a non-transactional Get() with the read policy set to STRONG (the default).
 * A transactional Query (which is by definition an ancestor Query and therefore a scan over the
 * entities in a single entity group) will also roll forward any unapplied jobs associated with the
 * entity group of the query before the query executes.
 *
 *
Unapplied jobs can also be rolled forward when the entity group with these jobs is groomed. In
 * production, the groomer is a background process that is continuously scanning and rolling forward
 * unapplied jobs. We considered implementing something similar, but it's nearly impossible to write
 * tests in an environment where you have a background process randomly adjusting your persistent
 * state, so we opted for a different approach: the local datastore groomer looks at all unapplied
 * jobs on every Get() and every Query(), and for each unapplied job, consults {@link
 * HighRepJobPolicy#shouldRollForwardExistingJob(Key)} to see if that job should be rolled forward.
 * This simulates grooming, but in a deterministic manner that makes testing much more
 * straightforward.
 *
 *
Note, however, that when the groomer rolls these jobs forward, it does so in such a way that
 * the result of the operation being performed is not affected. This is important, because it
 * guarantees that when a job fails to apply, a user who reads the entity group without any strong
 * consistency guarantees will always see the "old" version of the data in the entity group at least
 * once. Without this guarantee we would have jobs that failed to apply but whose failure was
 * invisible, which defeats the purpose of what we're trying to simulate.
 *
 */
// It's a little wonky to be using a low-level API object in the local
// datastore, but it's not unheard of.  Here's the reason we do it: This
// interface is exposed via the testing apis so that developers can provide
// their own implementations, and I'd much rather have people coding against
// Key, which is part of the public api, than Onestore.Path, which is not.
public interface HighRepJobPolicy {

  /**
   * Returns {@code true} if the new job should apply according to the policy, {@code false}
   * otherwise.
   *
   * @param entityGroup A unique identifier for the entity group.
   */
  boolean shouldApplyNewJob(Key entityGroup);

  /**
   * Returns {@code true} if the existing job should roll forward according to the policy, {@code
   * false} otherwise.
   *
   * @param entityGroup A unique identifier for the entity group.
   */
  boolean shouldRollForwardExistingJob(Key entityGroup);
}